Created
August 9, 2019 04:26
-
-
Save dynnt27/993ad31ba340fb918f2167f99ebce68a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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