Get the item that appears the most times in an array

做~自己de王妃 提交于 2020-01-08 17:18:31

问题


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?


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



回答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);



回答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;



回答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.




回答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]



回答6:


This version will quit looking when the count exceeds the number of items not yet counted.

It works without sorting the array.

Array.prototype.most= function(){
    var L= this.length, freq= [], unique= [], 
    tem, max= 1, index, count;
    while(L>= max){
        tem= this[--L];
        if(unique.indexOf(tem)== -1){
            unique.push(tem);
            index= -1, count= 0;
            while((index= this.indexOf(tem, index+1))!= -1){
                ++count;
            }
            if(count> max){
                freq= [tem];
                max= count;
            }
            else if(count== max) freq.push(tem);
        }
    }
    return [freq, max];
}

    //test
    var A= ["apples","oranges","oranges","oranges","bananas",
   "bananas","oranges","bananas"];
    alert(A.most()) // [oranges,4]

    A.push("bananas");
    alert(A.most()) // [bananas,oranges,4]



回答7:


I solved it this way for finding the most common integer

function mostCommon(arr) {
    // finds the first most common integer, doesn't account for 2 equally common integers (a tie)

    freq = [];

    // set all frequency counts to 0
    for(i = 0; i < arr[arr.length-1]; i++) {
      freq[i] = 0;
    }

    // use index in freq to represent the number, and the value at the index represent the frequency count 
    for(i = 0; i < arr.length; i++) {
      freq[arr[i]]++; 
    }

    // find biggest number's index, that's the most frequent integer
    mostCommon = freq[0];
    for(i = 0; i < freq.length; i++) {
      if(freq[i] > mostCommon) {
        mostCommon = i;
      }
    }

    return mostCommon;
} 



回答8:


This is my solution.

var max_frequent_elements = function(arr){
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
    if ( arr[i] !== prev ) {
        a.push(arr[i]);
        b.push(1);
    } else {
        b[b.length-1]++;
    }
    prev = arr[i];
}


var max = b[0]
for(var p=1;p<b.length;p++){
       if(b[p]>max)max=b[p]
 }

var indices = []
for(var q=0;q<a.length;q++){
   if(b[q]==max){indices.push(a[q])}
}
return indices;

};




回答9:


All the solutions above are iterative.

Here's a ES6 functional mutation-less version:

Array.prototype.mostRepresented = function() {
  const indexedElements = this.reduce((result, element) => {
    return result.map(el => {
      return {
        value: el.value,
        count: el.count + (el.value === element ? 1 : 0),
      };
    }).concat(result.some(el => el.value === element) ? [] : {value: element, count: 1});
  }, []);
  return (indexedElements.slice(1).reduce(
    (result, indexedElement) => (indexedElement.count > result.count ? indexedElement : result),
    indexedElements[0]) || {}).value;
};

It could be optimized in specific situations where performance is the bottleneck, but it has a great advantage of working with any kind of array elements.

The last line could be replaced with:

  return (indexedElements.maxBy(el => el.count) || {}).value;

With:

Array.prototype.maxBy = function(fn) {
  return this.slice(1).reduce((result, element) => (fn(element) > fn(result) ? element : result), this[0]);
};

for clarity




回答10:


If the array contains strings try this solution

    function GetMaxFrequency (array) {
    var store = array;
    var frequency = [];  // array of frequency.
    var result;   // holds the max frequency element.

    for(var v in store) {
        var target = store[v];
        var numOccurences = $.grep(store, function (elem) {
        return elem === target;
        }).length;
        frequency.push(numOccurences);

    }
    maxValue = Math.max.apply(this, frequency);
    result = store[$.inArray(maxValue,frequency)];
    return result;
}
var store = ['ff','cc','cc','ff','ff','ff','ff','ff','ff','yahya','yahya','cc','yahya'];
alert(GetMaxFrequency(store));



回答11:


A fairly short solution.

function mostCommon(list) {
  var keyCounts = {};
  var topCount = 0;
  var topKey = {};
  list.forEach(function(item, val) {
    keyCounts[item] = keyCounts[item] + 1 || 1;
    if (keyCounts[item] > topCount) {
      topKey = item;
      topCount = keyCounts[item];
    }
  });

  return topKey;
}

document.write(mostCommon(['AA', 'AA', 'AB', 'AC']))



回答12:


This solution returns an array of the most appearing numbers in an array, in case multiple numbers appear at the "max" times.

    function mode(numbers) {
      var counterObj = {}; 
      var max = 0;
      var result = [];
      for(let num in numbers) {
        counterObj[numbers[num]] = (counterObj[numbers[num]] || 0) + 1; 
        if(counterObj[numbers[num]] >= max) { 
          max = counterObj[numbers[num]];
        }
      }
      for (let num in counterObj) {
        if(counterObj[num] == max) {
          result.push(parseInt(num));
        }
      }
      return result;
    }


来源:https://stackoverflow.com/questions/3783950/get-the-item-that-appears-the-most-times-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!