Reputation: 422
For example I have input string with value "test test in string".
I need to do a function that will split every word and count each how many of them are in that string input.
The output should be like: test: 2, in: 1, string: 1
Thanks a lot in advance for tip.
Upvotes: 1
Views: 251
Reputation: 312
You can do like that.
var str = "test test test in string";
var res = str.split(" ");
var result = {};
res.forEach(function(x) {
result[x] = (result[x] || 0) + 1;
});
console.log(result)
Upvotes: 0
Reputation: 29282
after splitting the string, you can use reduce function to count the frequency of each word
const str = "test test in string";
const result = str.split(' ').reduce((acc, curr) => {
acc[curr] = acc[curr] ? ++acc[curr] : 1;
return acc;
}, {})
console.log(result);
Upvotes: 2
Reputation: 1517
If you are cool with lodash, then:
_.countBy('test test in string'.split(' '))
Upvotes: 0