Skip to content

Instantly share code, notes, and snippets.

@dynnt27
Created August 9, 2019 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dynnt27/993ad31ba340fb918f2167f99ebce68a to your computer and use it in GitHub Desktop.
Save dynnt27/993ad31ba340fb918f2167f99ebce68a to your computer and use it in GitHub Desktop.
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];
}
}
var sortable = [];
for (var key in modeMap) {
sortable.push([key, modeMap[key]]);
}
sortable.sort(function(a, b) {
return b[1] - a[1];
});
if (sortable[0][1] === sortable[1][1]) {
return sortable[1][1]
}
return maxEl;
}
mode([34,31,34,77,82])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment