a1tern4tive
a1tern4tive

Reputation: 422

JavaScript: Split and count words in string

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

Answers (3)

Vu Hoang Duc
Vu Hoang Duc

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

Yousaf
Yousaf

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

user0101
user0101

Reputation: 1517

If you are cool with lodash, then:

_.countBy('test test in string'.split(' '))

Upvotes: 0

Related Questions