计算有无大小写的数组中的相似词

时间:2018-08-13 07:27:01

标签: javascript arrays sorting

我有一个充满单词的数组,我需要计算用户选择是否忽略大小写对其排序的相似单词

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]]

2 个答案:

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