Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@abdus
Created August 3, 2019 14:14
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 abdus/218b4a1c19fb86e6c8ed11023787b81e to your computer and use it in GitHub Desktop.
Save abdus/218b4a1c19fb86e6c8ed11023787b81e to your computer and use it in GitHub Desktop.
get the most frequent element from an array. In other words, mode of an array
/**
* Getting the most frequent element from an array
*/
function mode(array = []) {
// check if it is an array and have atleast a single element
if (!Array.isArray(array)) {
throw new Error(`Please provide an array as argument`);
}
const counter = {};
let maxElement = [];
let maxCount = 1;
for (const element of array) {
if (!counter[element]) {
counter[element] = 1;
} else {
counter[element]++;
}
if (counter[element] > maxCount) {
maxElement = [element];
maxCount = counter[element];
} else if (counter[element] === maxCount) {
maxElement.push(element);
}
}
return maxElement;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment