Jrn Jrn - 1 year ago 58
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.


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

In this case I should get

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

In this case I also should get

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

Any help with this is welcome.

Answer Source

You could use something like this:

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

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download