I have to find the most common values in array in JavaScript.
my tried coded
eg arrays
var A = ["a", "c", "a", "b", "d", "e", "f"];
var B = ["a", "c", "a", "c", "d", "e", "f"];
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;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
and other one
var store = ['1','2','2','3','4'];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}
Code works ok in case A, "a" repeat most with 2 times occurrence, so I get "a" that's ok.
but in case of B, "a" & "c" both repeat 2 times but I get only A, but my requirement is to get both "a" & "c".