Sunday, April 28, 2024
 Popular · Latest · Hot · Upcoming
194
rated 0 times [  199] [ 5]  / answers: 1 / hits: 173620  / 15 Years ago, sat, june 27, 2009, 12:00:00

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.


More From » mode

 Answers
30

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;
}

[#99227] Wednesday, June 24, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;