0

I need to write a function that counts the frequencies of each word in the string in the given parameter of a function. I was wondering, what is the best way to do this?

For example, if the string in the parameter was "Mark cow mark cow the" The count for each word would be:

Mark: 1
mark: 1
cow: 2
the: 1

My function:

function calcFrequencies(s){
   var a = [], b = [], prev;
   var words = s.split(" ");
    for ( var i = 0; i < words.length; i++ ) {
    }
}

Just to clarify, I am okay with whatever solution you come up with, I just figured it probably could involve splitting and looping through arrays, I just can't seem to figure it out.

Trobosko
  • 23
  • 4

1 Answers1

2

You can create a Map to keep track of the count of each word.

function calcFrequencies(s) {
  let count = new Map();
  var words = s.split(" ");

  words.forEach(word => {
    let c = count.get(word) || 0;  
    c++;  
    count.set(word, c);
  });

  return count;
}

let result = calcFrequencies("Mark cow mark cow the");

for (let [key, value] of result.entries()) {
  console.log(key + ": " + value);
}
Nikhil
  • 6,493
  • 10
  • 31
  • 68
  • 1
    I'd say `Map` "should" be used, not "can". The object version is fragile, e.g. `countFrequences("lego constructor")` – georg Oct 30 '19 at 19:36
  • That's right @georg. Didn't expect it to break that way. I'll edit the answer. – Nikhil Oct 30 '19 at 19:37