Get the item that appears the most times in an array

25,026

Solution 1

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

Solution 2

Solution with emphasis to Array.prototype.forEach and the problem of getting more than one key if the max count is shared among more items.

Edit: Proposal with one loop, only.

var store = ['1', '2', '2', '3', '4', '5', '5'],
    distribution = {},
    max = 0,
    result = [];

store.forEach(function (a) {
    distribution[a] = (distribution[a] || 0) + 1;
    if (distribution[a] > max) {
        max = distribution[a];
        result = [a];
        return;
    }
    if (distribution[a] === max) {
        result.push(a);
    }
});
console.log('max: ' + max);
console.log('key/s with max count: ' + JSON.stringify(result));
console.log(distribution);

Solution 3

arr.sort();
    var max=0,result,freq = 0;
    for(var i=0; i < arr.length; i++){
        if(arr[i]===arr[i+1]){
            freq++;
        }
        else {
            freq=0;
        }
        if(freq>max){
            result = arr[i];
            max = freq;
        }
    }
    return result;

Solution 4

Make a histogram, find the key for the maximum number in the histogram.

var hist = [];
for (var i = 0; i < store.length; i++) {
  var n = store[i];
  if (hist[n] === undefined) hist[n] = 0;
  else hist[n]++;
}

var best_count = hist[store[0]];
var best = store[0];
for (var i = 0; i < store.length; i++) {
  if (hist[store[i]] > best_count) {
    best_count = hist[store[i]];
    best = store[i];
  }
}

alert(best + ' occurs the most at ' + best_count + ' occurrences');

This assumes either there are no ties, or you don't care which is selected.

Solution 5

If the array is sorted this should work:

function popular(array) { 
   if (array.length == 0) return [null, 0];
   var n = max = 1, maxNum = array[0], pv, cv;

   for(var i = 0; i < array.length; i++, pv = array[i-1], cv = array[i]) {
      if (pv == cv) { 
        if (++n >= max) {
           max = n; maxNum = cv;
        }
      } else n = 1;
   }

   return [maxNum, max];
};

popular([1,2,2,3,4,9,9,9,9,1,1])
[9, 4]

popular([1,2,2,3,4,9,9,9,9,1,1,10,10,10,10,10])
[10, 5]
Share:
25,026
p0larBoy
Author by

p0larBoy

Javascript all day, err day...

Updated on July 16, 2022

Comments

  • p0larBoy
    p0larBoy almost 2 years
    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?