Get the element with the highest occurrence in an array

后端 未结 30 1548
野性不改
野性不改 2020-11-22 11:17

I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

[\'pear\', \'a         


        
30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 12:04

    function mode(arr){
      return arr.reduce(function(counts,key){
        var curCount = (counts[key+''] || 0) + 1;
        counts[key+''] = curCount;
        if (curCount > counts.max) { counts.max = curCount; counts.mode = key; }
        return counts;
      }, {max:0, mode: null}).mode
    }
    

提交回复
热议问题