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"));
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With