Created
August 3, 2019 14:14
-
-
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
This file contains 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
/** | |
* 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