Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the element with the highest occurrence in an array

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

For example, in

['pear', 'apple', 'orange', 'apple'] 

the 'apple' element is the most frequent one.

like image 498
vise Avatar asked Jun 27 '09 23:06

vise


People also ask

How do you find the maximum occurrence of an element in an array?

Navigate the array. Update the array as for ith index :- arrA[arrA[i]% n] = arrA[arrA[i]% n] + n; Now navigate the updated array and check which index has the maximum value, that index number is the element which has the maximum occurrence in the array.


2 Answers

This is just the mode. Here's a quick, non-optimized solution. It should be O(n).

function mode(array) {     if(array.length == 0)         return null;     var modeMap = {};     var maxEl = array[0], maxCount = 1;     for(var i = 0; i < array.length; i++)     {         var el = array[i];         if(modeMap[el] == null)             modeMap[el] = 1;         else             modeMap[el]++;           if(modeMap[el] > maxCount)         {             maxEl = el;             maxCount = modeMap[el];         }     }     return maxEl; } 
like image 67
Matthew Flaschen Avatar answered Sep 20 '22 06:09

Matthew Flaschen


There have been some developments in javascript since 2009 - I thought I'd add another option. I'm less concerned with efficiency until it's actually a problem so my definition of "elegant" code (as stipulated by the OP) favours readability - which is of course subjective...

function mode(arr){     return arr.sort((a,b) =>           arr.filter(v => v===a).length         - arr.filter(v => v===b).length     ).pop(); }  mode(['pear', 'apple', 'orange', 'apple']); // apple 

In this particular example, should two or more elements of the set have equal occurrences then the one that appears latest in the array will be returned. It's also worth pointing out that it will modify your original array - which can be prevented if you wish with an Array.slice call beforehand.


Edit: updated the example with some ES6 fat arrows because 2015 happened and I think they look pretty... If you are concerned with backwards compatibility you can find this in the revision history.

like image 35
Emissary Avatar answered Sep 19 '22 06:09

Emissary