Reputation: 573
I need to get the total count of each word in a string .
I wanted to achieve it using reducer since i am a beginner in the reduce method i could not solve it .
getWordOccurence = (str1) => {
splitStr = str1.split(' ');
let count=0;
const wordCount = splitStr.reduce((acc, curr) => ({...acc,[curr]:count}),{})
console.log(wordCount)
};
getWordOccurence('apple orange apple banana grapes ?');
Expected : {"apple":2,"orange":1,"banana":1,"grape":1}
Upvotes: 1
Views: 81
Reputation: 19070
You can String.prototype.split() the string
and use Array.prototype.reduce() to obtain the result object
In case you need to exclude the non words you can do Regular Expression /[a-z]/i
to check the String.prototype.match() c.match(/[a-z]/i)
Code:
const str = 'apple orange apple banana grapes ?';
const getWordOccurence = s => s.split(' ').reduce((a, c) => {
if (c.match(/[a-z]/i)) { // Only words...
a[c] = (a[c] || 0) + 1;
}
return a;
}, {});
const result = getWordOccurence(str);
console.log(result);
Upvotes: 0
Reputation: 10591
I'd like to post a pure reducer version.
const getWordOccurence = (str1) => {
const splitStr = str1.split(' ');
const wordCount = splitStr.reduce((acc, x)=>({...acc,[x]:acc[x]+1||1}),{})
console.log(wordCount)
};
getWordOccurence('apple orange apple banana grapes ?');
otherwise, I recommend simply use accumulator and loop through object (you can always extract it to a function, like occurence
or something, you don't even need to pass the {}
then).
const getWordOccurence = (str1) => {
const words = str1.split(' ');
//function occurence(words){
let acc={};
for(let word of words)
acc[word] = acc[word]+1 || 1
//return acc}
//const wordCount = occurence(words)
const wordCount = acc //just in case you want a *const* result
console.log(wordCount)
};
getWordOccurence('apple orange apple banana grapes ?');
Upvotes: 0
Reputation: 36564
You can try using comma operator. I thinks its better to use comma operator to return accumulator rather than using spread operator.
const getWordOccurence = (str1) => {
splitStr = str1.split(' ');
const wordCount = splitStr.reduce((ac, x) => (ac[x] = ac[x] + 1 || 1,ac),{})
console.log(wordCount)
};
getWordOccurence('apple orange apple banana grapes ?');
One line for the function will be
const getWordOccurence = (str) => str.split(' ').reduce((ac,a) => (ac[a] = ac[a] + 1 || 1,ac),{})
console.log(getWordOccurence('apple orange apple banana grapes ?'));
Upvotes: 2