使用array.reduce方法计算重复元素

ZAR*_*ZAR 4 javascript arrays reduce

我正在编写关于功能JS的教程,我需要使用reduce方法来应对挑战:

给定一个随机数组的单词,输出一个显示单词加上单词数的数组,例如:['apple, 'orange, 'grape', 'apple']- >['apple: 2','orange: 1', 'grape: 1]

我知道这不是reduce的正确用法,但这是我的半工作解决方案:

var wordCountsArray = inputWords.map(function(item){
    var counter = 0;
    var itemCount = inputWords.reduce(function(prevVal, curVal){
        if(curVal==item){
            counter++;
        }
        return;
    },0);

    return item+": "+counter;
})

return wordCountsArray;  

}
Run Code Online (Sandbox Code Playgroud)

这确实输出了单词计数,但单词计数列表有重复,即看起来像:

['apple: 2','orange: 1', 'grape: 1, 'apple: 2']
Run Code Online (Sandbox Code Playgroud)

代替

['apple: 2','orange: 1', 'grape: 1]
Run Code Online (Sandbox Code Playgroud)

我查阅了MSDN的方法指南,Mozilla的,几个博客.我得到它作为累加器如何工作,但因为它使用最后一次迭代的输出作为下一个的输入,我不知道如何将它应用于此任务.我不需要解决方案,但在理解方面可能有点帮助?

Mon*_*dia 7

我知道这是一个解决方案,但有时解决方案是最好的解释.在第一个块中跟随"fruitsCount"对象.请注意,"fruitsArray"只是这个对象的翻译,所以应该很容易理解.

var fruits = ['apple', 'orange', 'grape', 'apple'].reduce(function(fruitsCount, currentFruit){
    if(typeof fruitsCount[currentFruit] !== "undefined"){
      fruitsCount[currentFruit]++; 
      return fruitsCount;
    } else {
        fruitsCount[currentFruit]=1; 
        return fruitsCount;
    }
}, {});

var fruitsArray = [];
for(var x in fruits){
    fruitsArray.push(x + ": " + fruits[x]);
}

console.log(fruitsArray);
Run Code Online (Sandbox Code Playgroud)

  • `fruitsCount [currentFruit] =(fruitsCount [currentFruit] || 0)+ 1` (6认同)