p0larBoy p0larBoy - 4 months ago 9
Javascript Question

Get the item that appears the most times in an array

var store = ['1','2','2','3','4'];


I want to find out that
2
appear the most in the array. How do I go about doing that?

Answer

I would do something like:

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.
        }
}
Comments