Skip to content

Instantly share code, notes, and snippets.

@WonRhee
Created December 20, 2016 08:31
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 WonRhee/305c195433989851f84a2dd98c87ad3d to your computer and use it in GitHub Desktop.
Save WonRhee/305c195433989851f84a2dd98c87ad3d to your computer and use it in GitHub Desktop.
Given array of integers, find its mode. (the number which appears most often in it)
// Given array of integers, find its mode. (the number which appears most often in it)
function arrayMode(sequence) {
var arr = {};
for (var i=0; i < sequence.length; i++) {
var num = sequence[i];
if (arr[num] === undefined){
arr[num] = 0;
}
arr[num] += 1;
}
var greatest = 0;
var mode = 0;
Object.keys(arr).forEach(function(key) {
if (arr[key] > greatest) {
greatest = arr[key];
mode = key;
}
});
return parseInt(mode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment