Word in array counter

please format code with </> button * homework policy * asking questions

Hello, I am getting a bit confused here… I need to count how many times the word imagine shows up in the array but I do not know how to create the counter so it works and is printed… thank you! Any guidance is very welcomed.

var parrafo = "Imagine there's no heaven | It's easy if you try | No hell below us | Above us only sky | Imagine all the people | Living for today | Imagine there's no countries | It isn't hard to do | Nothing to kill or die for | And no religion too | Imagine all the people | Living life in peace";
var parrafo_array;
var contador;

function setup() {
  createCanvas(1024, 768);
  background("white");
  fill(50);
  textSize(20);
  contador = 0;

 for (var i=0; i< 61; i++) {
   if (parrafo [i] = true) {
   contador = contador + 1;
   } if else {
   contador = contador;
   }
 text(contador, 10, 10); 
}

You’re using the assignment operator = instead of the equality operator ==:

Also you still need to splitTokens() your lyrics string so it becomes an array of words.

Only then you can count each word inside that array which matches string “imagine”.

2 Likes

Hi

1 Like

Why not just using RegEx and do something like (just as example):

const wordCounter = (myString,mySearchString) => ((myString).match(new RegExp('\\b'+mySearchString+'\\b',"g")) || []).length;

let pinfo;
let itext;
let isearch;

function setup() {
  noCanvas();
  createElement("label").html("Search String: ");    
  isearch = createInput("Imagine");
  createElement("br");
  createElement("label").html("Text To Search: ");
  itext   = createInput("Imagine there's no heaven | It's easy if you try | No hell below us | Above us, only sky | Imagine all the people | Livin' for today | Ah | Imagine there's no countries | It isn't hard to do | Nothing to kill or die for | And no religion, too | Imagine all the people | Livin' life in peace | You | You may say I'm a dreamer | But I'm not the only one | I hope someday you'll join us | And the world will be as one | Imagine no possessions | I wonder if you can | No need for greed or hunger | A brotherhood of man | Imagine all the people | Sharing all the world | You | You may say I'm a dreamer | But I'm not the only one | I hope someday you'll join us | And the world will live as one");  
  itext.input(function() {
      pinfo.html("The word " + isearch.value() + " was found " +   wordCounter(this.value(),isearch.value()) + " time(s)");  
  });  
  pinfo = createP();  
}

dummy2

Cheers
— mnse

2 Likes