sahil sahil - 17 days ago 5
Javascript Question

Return an object with properties for each of the word in the wordlist

I am trying to implement a frequency function which should return an object with properties for each of the words in the wordlist. The values of the properties should be how many times the word is present in text. I am able to only return the number of counts, but I could not figure out how to return an object. The answer should be an object like {"bar": 2, "foo": 3}.

function frequencies(str,wordlist){

var count = 0;
var count2 = 0;
var freqw = {};
var text1 = str.split(' ');
for(var i = 0; i < wordlist.length; i++){
if(str.match(wordlist[i]))
count++;
}
return count;
}

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

Answer

You need to use indexOf instead of match and also loop over the input string instead of the wordlist

function frequencies(str,wordlist){

    var count = 0;
    var count2 = 0;
    var freqw = {};
    var text1 = str.split(' ');
    for(var i = 0; i < wordlist.length; i++){
        freqw[wordlist[i]] = 0;

    }

    for(var i = 0; i < text1.length; i++){
        if(freqw[text1[i]] !== undefined)  //check if word exists
            freqw[[text1[i]]]++;
    }
    return freqw;
}

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