Skip to content

Instantly share code, notes, and snippets.

@bbatliner
Created March 17, 2016 17:04
Show Gist options
  • Save bbatliner/d9e46abdb23613f99e07 to your computer and use it in GitHub Desktop.
Save bbatliner/d9e46abdb23613f99e07 to your computer and use it in GitHub Desktop.
function multimode(arr) {
const counts = new Map();
for (let i = 0; i < arr.length; i++) {
counts.set(arr[i], (counts.get(arr[i]) || 0) + 1);
}
let maxCount, maxElem;
counts.forEach((count, index) => {
if (maxCount === undefined || count > maxCount) {
maxCount = count;
maxElem = index;
} else if (count === maxCount) {
maxElem = Array.isArray(maxElem) ? maxElem.concat(index) : [maxElem, index];
}
});
return maxElem;
}
multimode([1,2,3,3]); // 3
multimode([1,2,2,3,3]); // [2, 3]
multimode([1,2,3]); // [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment