Get the element with the highest occurrence in an array

后端 未结 30 1274
野性不改
野性不改 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 11:54

    You could solve it in O(n) complexity

    var arr = [1,3,54,56,6,6,1,6];
    var obj = {};
    
    /* first convert the array in to object with unique elements and number of times each element is repeated */
    for(var i = 0; i < arr.length; i++)
    {
       var x = arr[i];
       if(!obj[x])
         obj[x] = 1;
       else 
         obj[x]++;
    }
    
    console.log(obj);//just for reference
    
    /* now traverse the object to get the element */
    var index = 0;
    var max = 0;
    
    for(var obIndex in obj)
    {
      if(obj[obIndex] > max)
      {
        max = obj[obIndex];
        index = obIndex;
      }
    }
    console.log(index+" got maximum time repeated, with "+ max +" times" );
    

    Just copy and paste in chrome console to run the above code.

提交回复
热议问题