Get the item that appears the most times in an array

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

    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]
    

提交回复
热议问题