我有一个充满单词的数组,我需要计算用户选择是否忽略大小写对其排序的相似单词
function parseText(text,letterCase,punc) {
var words = text
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, '')
.split(/\s/); //split the array and remove punctualitis
words.forEach(function(w) {
if (!Sub_Word[w]) {
Sub_Word[w] = 0;
}
Sub_Word[w]+=1;//creating an array and the word and how much it was there
});
return Sub_Word;
}
现在此代码有效,但在某些情况下不起作用,例如此数组["he","He","hello"]
我需要它返回[["he:2"],[hello:1]]
答案 0 :(得分:3)
使用array.reduce:
var words = ["he","He","hello"];
var res = words.reduce((m, o) => {
o = o.toLowerCase();
var found = m.find(e => e[0] === o);
found ? found[1]++ : m.push([o, 1]);
return m;
}, []);
console.log(res);
答案 1 :(得分:1)
您可以使用Array.reduce()
和Object.entries()
:
let arr = ["he","He","hello"];
let lettercase = true;
let result = Object.entries(arr.reduce((a,curr)=>{
let key = lettercase ? curr.toLowerCase() : curr;
a[key] = a[key] || 0;
a[key]++;
return a;
},{}));
console.log(result);