I’m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.
For example, in
JavaScript
x
2
1
['pear', 'apple', 'orange', 'apple']
2
the 'apple'
element is the most frequent one.
Advertisement
Answer
This is just the mode. Here’s a quick, non-optimized solution. It should be O(n).
JavaScript
1
22
22
1
function mode(array)
2
{
3
if(array.length == 0)
4
return null;
5
var modeMap = {};
6
var maxEl = array[0], maxCount = 1;
7
for(var i = 0; i < array.length; i++)
8
{
9
var el = array[i];
10
if(modeMap[el] == null)
11
modeMap[el] = 1;
12
else
13
modeMap[el]++;
14
if(modeMap[el] > maxCount)
15
{
16
maxEl = el;
17
maxCount = modeMap[el];
18
}
19
}
20
return maxEl;
21
}
22