Get the element with the highest occurrence in an array

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

    Here is my way. I try to group data fist.

    const _ = require("underscore")
    
    var test  = [ 1, 1, 2, 1 ];
    var groupResult = _.groupBy(test, (e)=> e);
    

    The groupResult should be

    {
      1: [1, 1, 1]
      2: [2] 
    }
    

    Then find the property which has the longest array

    function findMax(groupResult){
       var maxArr = []
       var max;
       for(var item in groupResult){
         if(!max) { 
            max = { value:item, count: groupResult[item].length } ; 
            maxArr.push(max); 
            continue;
         }
         if(max.count < groupResult[item].length){ 
            maxArr = [];
            max = { value:item, count: groupResult[item].length }
            maxArr.push(max)
         } else if(max === groupResult[item].length)
            maxArr.push({ value:item, count: groupResult[item].length })
       }
       return maxArr;
    }
    

    The complete code looks like

    const _ = require("underscore")
    
    var test  = [ 1, 1, 2, 1 ];
    var groupResult= _.groupBy(test, (e)=> e);
    console.log(findMax(groupResult)[0].value);
    
    function findMax(groupResult){
       var maxArr = []
       var max;
       for(var item in groupResult){
         if(!max) { 
            max = { value:item, count: groupResult[item].length } ; 
            maxArr.push(max); 
            continue;
         }
         if(max.count < groupResult[item].length){ 
            maxArr = [];
            max = { value:item, count: groupResult[item].length }
            maxArr.push(max)
         } else if(max === groupResult[item].length)
            maxArr.push({ value:item, count: groupResult[item].length })
       }
       return maxArr;
    }
    

提交回复
热议问题