Using array.reduce method to count duplicate elements [duplicate]

China☆狼群 提交于 2019-12-07 09:38:40

问题


I'm working through a tutorial on functional JS and I'm up to a challenge requiring the use of the reduce method:

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]

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

instead of

['apple: 2','orange: 1', 'grape: 1]

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?


回答1:


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


来源:https://stackoverflow.com/questions/24252305/using-array-reduce-method-to-count-duplicate-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!