EdgarA EdgarA - 22 days ago 8
Javascript Question

Word frequency counter on specific words using javascript

I need to count number of predetermined words (wordlist) in a text. This is what I have done so far:

function frequencies(text, wordlist){
var words = text.split(/\s/);
var freqMap = {};
words.forEach(function(w){
if (!freqMap[w] && wordlist){
freqMap[w] = 0;
}
freqMap[w] += 1;
});
return freqMap;

}


At the moment it counts all the words in given text, how do I make it count only words given in wordlist?

Answer

Check word is in given list using Array#indexOf method( or Array#includes method).

function frequencies(text, wordlist) {
  var words = text.split(/\s/);
  var freqMap = {};
  words.forEach(function(w) {
    if (wordlist && wordlist.indexOf(w) > -1) { // or wordlist.includes(w)
      if (!freqMap[w]) {
        freqMap[w] = 0;
      }
      freqMap[w] += 1;
    }
  });
  return freqMap;
}