1

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.

1
  • @Yousaf sure, I've splited that string input, but I don't know how to count frequency of words. Commented May 27, 2020 at 10:58

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

If you are cool with lodash, then:

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.