Get the element with the highest occurrence in an array

后端 未结 30 1716
野性不改
野性不改 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:03

    var cats = ['Tom','Fluffy','Tom','Bella','Chloe','Tom','Chloe'];
    var counts = {};
    var compare = 0;
    var mostFrequent;
    (function(array){
       for(var i = 0, len = array.length; i < len; i++){
           var word = array[i];
    
           if(counts[word] === undefined){
               counts[word] = 1;
           }else{
               counts[word] = counts[word] + 1;
           }
           if(counts[word] > compare){
                 compare = counts[word];
                 mostFrequent = cats[i];
           }
        }
      return mostFrequent;
    })(cats);
    

提交回复
热议问题