Get the item that appears the most times in an array

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

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

提交回复
热议问题