'How to calculate frequency of word in text

How can I implement javascript function to calculate frequency of word in text

frequencies('foo foo bar foo   bar buz', ['foo', 'bar']);

should return {"bar": 2, "foo": 3}


Solution 1:[1]

If you can use underscore/lodash its as simple as:

function frequencies(str) {
  return _.countBy(str.split(' '));
}

Solution 2:[2]

How about this:

function frequencies(str, words){
    var ret = {}, split = str.split(' ');

    for(var i = 0; i < split.length; i++){
        var currentWord = split[i];
        if(!currentWord || !~words.indexOf(currentWord)) continue;
        ret[currentWord] = !ret[currentWord] ? 1 : ret[currentWord]+1;
    }

    return ret;
}

console.log(frequencies('foo foo bar foo   bar buz', ['foo', 'bar']));

http://jsfiddle.net/uqgtqy01/1/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tengbretson
Solution 2