简体   繁体   中英

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 https://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.

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.

ES2015

If ES2015 is an option, you could use this one. It's less code.

function mostFrequent(array) {
    let map = array.map((a) => array.filter((b) => a === b).length);

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

And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map) for Math.max(...map) !

Try this:

 const mostFrequent = arr => { let maxCount = 0; const occurrences = new Map(); arr.forEach(x => { const count = occurrences.has(x) ? occurrences.get(x) + 1 : 1; occurrences.set(x, count); maxCount = count > maxCount ? count : maxCount; }); return Array.from(occurrences).find(([element, count]) => count === maxCount)[0]; }; console.log(mostFrequent(['25', '50', 'a', 'a', 'b', 'c'])); console.log(mostFrequent(['75', '100', 'a', 'b', 'b', 'a'])); 

It basically the same solution as in Get the element with the highest occurrence in an array , only the last line is significant: instead of returning the last maxElement , it returns the first element in the occurrences map that has the same count as maxCount .

Beside the given solutions, this proposal has a complexity of O(n) - a single loop only.

Basically there are two objects, one hash table and one result set, which are maintained through iteration.

 function getValue(array) { var count = 0, index = -1; array.forEach(function (a, i) { this[a] = this[a] || { count: 0, index: i }; this[a].count++; if (this[a].count > count) { count = this[a].count; index = this[a].index; return; } if (this[a].count === count && this[a].index < index) { index = this[a].index; } }, Object.create(null)); return array[index]; } console.log(getValue(['25', '50', 'a', 'a', 'b', 'c'])); console.log(getValue(['25', '50', 'a', 'b', 'b', 'a', 'c'])); 

EDITED: new jsfiddle.

Like this: https://jsfiddle.net/Ldohv125/1/

var array = ['75', '100', 'b', 'b', 'a', 'a'];
var mf = 1;
var m = 0;
var item;
for (var i=0; i<array.length; i++){
    for (var j=i; j<array.length; j++) {
        if (array[i] == array[j])
            m++;
        if (mf<m){
            mf=m; 
            item = array[i];
        }
     }
     m=0;
}
alert(item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM