使用array.reduce方法计算重复元素 [英] Using array.reduce method to count duplicate elements
问题描述
我正在编写一个关于函数JS的教程,我需要使用reduce方法的挑战:
I'm working through a tutorial on functional JS and I'm up to a challenge requiring the use of the reduce method:
给出一个随机数组的单词,输出一个数组,显示单词加上它的单词数,例如: ['apple,'orange,'grape','apple']
- > ['apple:2','orange:1','grape:1]
Given a random array of words, output an array that shows the word plus it's word count, for instance: ['apple, 'orange, 'grape', 'apple']
-> ['apple: 2','orange: 1', 'grape: 1]
我知道这不正确使用reduce,但这是我的半工作解决方案:
I know this isn't the correct use of reduce, but here was my semi-working solution:
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;
}
这确实输出了字数,但字数列表有重复,即看起来像:
This did indeed output the word counts, but the word count list has duplicates, i.e. looks like:
['apple: 2','orange: 1', 'grape: 1, 'apple: 2']
而不是
['apple: 2','orange: 1', 'grape: 1]
我查了MSDN的方法指南,Mozilla的,几个博客。我得到它作为累加器如何工作,但因为它使用最后一次迭代的输出作为下一个的输入,我不知道如何将它应用于此任务。我不需要解决方案,但也许需要帮助理解?
I've looked up MSDN's guide on the method, Mozilla's, several blogs. I get how it works as an accumulator, but because it uses the output of the last iteration as input for the next, I have no idea how to apply it to this task. I don't need a solution, but maybe a little help in understanding?
推荐答案
我知道这是一个解决方案,但有时候解决方案是最好的解释。在第一个块中跟随fruitsCount对象。请注意,fruitsArray只是该对象的翻译,所以应该很容易理解。
I know this is a solution, but sometimes solutions are the best explanations. Follow the "fruitsCount" object in the first block. Note that "fruitsArray" is simply a translation of this object, so that should be very easy to understand.
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);
这篇关于使用array.reduce方法计算重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!