abu
abu

Reputation: 147

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}

Upvotes: 0

Views: 221

Answers (3)

filur
filur

Reputation: 1556

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/

Upvotes: 0

tengbretson
tengbretson

Reputation: 169

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

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

Upvotes: 0

adeneo
adeneo

Reputation: 318222

Something like this should do that

function frequencies(str, opts) {
    var o = {};
    opts.forEach(function(opt) { o[opt] = 0; });
    str.split(/\s+/).forEach(function(x) { if (x in o) o[x]++; });

    return o;
}

FIDDLE

Upvotes: 4

Related Questions