Get the item that appears the most times in an array

后端 未结 12 1488
太阳男子
太阳男子 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:28

    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']))

提交回复
热议问题