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

[亡魂溺海] 提交于 2019-12-05 12:29:14

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