Get the item that appears the most times in an array

后端 未结 12 1522
太阳男子
太阳男子 2020-11-27 19:18
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?

12条回答
  •  清歌不尽
    2020-11-27 19:34

    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.

提交回复
热议问题