简体   繁体   English

计算字符串中每个单词的出现并将其放入对象中

[英]Count the occurence of each words in a string and put it in an object

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 . 我想使用reducer来实现它,因为我是reduce方法的初学者,我无法解决它。

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} 预期的:{“苹果”:2,“橙色”:1,“香蕉”:1,“葡萄”:1}

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

You can String.prototype.split() the string and use Array.prototype.reduce() to obtain the result object 您可以String.prototype.split() string并使用Array.prototype.reduce()获得结果object

In case you need to exclude the non words you can do Regular Expression /[az]/i to check the String.prototype.match() c.match(/[az]/i) 如果您需要排除非单词,则可以执行正则表达式 /[az]/i来检查String.prototype.match() c.match(/[az]/i)

Code: 码:

 const str = 'apple orange apple banana grapes ?'; const getWordOccurence = s => s.split(' ').reduce((a, c) => { if (c.match(/[az]/i)) { // Only words... a[c] = (a[c] || 0) + 1; } return a; }, {}); const result = getWordOccurence(str); console.log(result); 

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). 否则,我建议只使用蓄电池和遍历对象(你可以随时将其解压缩到一个功能,如occurence什么的,你甚至都不需要通过{}则)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM