Skip to content

Instantly share code, notes, and snippets.

@miladd3
Last active September 2, 2018 06:29
Show Gist options
  • Save miladd3/7d962f851b2101249b219228cc897ab9 to your computer and use it in GitHub Desktop.
Save miladd3/7d962f851b2101249b219228cc897ab9 to your computer and use it in GitHub Desktop.
Get most repeated item in a array using pure js
/**
* 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