Last active
September 2, 2018 06:29
-
-
Save miladd3/7d962f851b2101249b219228cc897ab9 to your computer and use it in GitHub Desktop.
Get most repeated item in a array using pure js
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
/** | |
* get most repeated item in an array with help of this article | |
* https://stackoverflow.com/questions/1053843/ | |
* | |
* @param {Array} array | |
* @returns {*} | |
*/ | |
var getMostRepeatedItem: function (array) { | |
if(array.length === 0) | |
return null; | |
var modeMap = {}; | |
var maxEl = array[0], maxCount = 1; | |
for(var i = 0; i < array.length; i++) | |
{ | |
var el = array[i]; | |
if(modeMap[el] == null) | |
modeMap[el] = 1; | |
else | |
modeMap[el]++; | |
if(modeMap[el] > maxCount) | |
{ | |
maxEl = el; | |
maxCount = modeMap[el]; | |
} | |
} | |
return maxEl; | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment