Jrn Jrn - 1 month ago 5
Javascript Question

Highest occurrence in an array or first selected

I'm trying to get the highest occurrence of a array value, and if there's an equal occurrence, I should get the first selected value of the equal occurrences.

Example:

var array = ['25', '50', 'a', 'a', 'b', 'c']


In this case I should get
a


var array = ['75', '100', 'a', 'b', 'b', 'a']


In this case I also should get
a


I've done my fair share of searching and found a couple of helpfull posts, these for example:



Somehow I can't seem to modify these examples to work for my case.

Right now I'm using the code below, but its returning the last selected equal occurrence, instead of the first. (credit http://stackoverflow.com/users/1238344/emissary)

function mostFrequent(array){
return array.sort(function(a,b){
return array.filter(function(v){ return v===a }).length
- array.filter(function(v){ return v===b }).length
}).pop();
}


Any help with this is welcome.

Answer

You could use something like this:

function mostFrequent(array) {
    var map = array.map(function(a) {
        return array.filter(function(b) {
            return a === b;
        }).length;
    });

    return array[map.indexOf(Math.max.apply(null, map))];
}

First it creates a map of occurrences of all the values. Next just check with Math.max which one is the highest. Check the indexOf for the first value that has that highest occurences and return the value of that index in the original array.