Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created February 18, 2015 03:50
Show Gist options
  • Save gartenfeld/3b9c83b7d90eefac930d to your computer and use it in GitHub Desktop.
Save gartenfeld/3b9c83b7d90eefac930d to your computer and use it in GitHub Desktop.
Finding a mode in an array of numbers.
var array = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17],
c = {}, // counters
s = []; // sortable array
for (var i=0; i<array.length; i++) {
c[array[i]] = c[array[i]] || 0; // initialize
c[array[i]]++;
} // count occurrences
for (var key in c) {
s.push([key, c[key]])
} // build sortable array from counters
s.sort(function(a, b) {return b[1]-a[1];});
var firstMode = parseInt(s[0][0]);
console.log(firstMode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment