How can I modify this function so that instead of showing me the most popular value it shows me the 3 most popular values, with popular I mean the values that are repeated the most in the array.
Function
function mode(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;6
}else{
modeMap[el]++;
}
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
array example
["PHP", "Joomla", "PHP", "PHP", "PHP", "Joomla", "PHP", "PHP", "Joomla", "Wordpress", "PHP", "PHP", "Joomla", "Joomla", "PHP", "Joomla", "PHP", "Joomla", "PHP", "Joomla", "PHP", "PHP", "PHP", "PHP", "PHP", "PHP", "NodeJS", "Joomla", "PHP"]0: "PHP"1: "Joomla"2: "PHP"3: "PHP"4: "PHP"5: "Joomla"6: "PHP"7: "PHP"8: "Joomla"9: "Wordpress"10: "PHP"11: "PHP"12: "Joomla"13: "Joomla"14: "PHP"15: "Joomla"16: "PHP"17: "Joomla"18: "PHP"19: "Joomla"20: "PHP"21: "PHP"22: "PHP"23: "PHP"24: "PHP"25: "PHP"26: "NodeJS"27: "Joomla"28: "PHP"length: 29__proto__: Array[0]
Instead of modifying your function I am going to propose a new one.
To get the result you are looking for you could do this:
We create an object (
hash
) where we will keep track of the number of times the appearsvalor
in the array.With
.forEach()
we go through the arrangement and inhash
it the account of the appearances.Then with
Object.keys
, we obtain an array with the keys ofhash
and with the method.sort
we order the array.In this way, you will get a
array
with thosevalores
ordered descending according to the number of appearances in thearray
initial.For example:
// UPDATE
If you also need to know which
número de ocurrencias
of eachvalor
, you could do it like this:.reduce()
we traverse the array and obtain aarray
ofobject
, where eachobject
has the propertiesvalue
(value in thearray
initial) andcount
(number of occurrences).