Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting words in javascript and push it into an object

I want to achieve a javascript program that count through a word and return the word and the number of times it appears eg {hello : 2, "@hello":1, world : 1, toString:1}

below is my code but i only get the total number of words

function words(str) { 
    app = {};
    return str.split(" ").length;
}

console.log(words("hello world"));   
like image 718
Iakhator Avatar asked Oct 18 '16 07:10

Iakhator


1 Answers

Use reduce to iterate the words array, and count the instances:

function words(str) { 
    return str.split(" ").reduce(function(count, word) {
      count[word] = count.hasOwnProperty(word) ? count[word] + 1 : 1;
      
      return count;
    }, {});
}

console.log(words("reserved words like prototype and toString ok? Yes toString is fine"));
like image 140
Ori Drori Avatar answered Sep 21 '22 08:09

Ori Drori