Created
February 18, 2015 03:50
-
-
Save gartenfeld/3b9c83b7d90eefac930d to your computer and use it in GitHub Desktop.
Finding a mode in an array of numbers.
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
| 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