Get the item that appears the most times in an array

后端 未结 12 1442
太阳男子
太阳男子 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;
        }
    
    0 讨论(0)
  • 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']))

    0 讨论(0)
  • 2020-11-27 19:29

    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]
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 19:36

    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;
    

    };

    0 讨论(0)
提交回复
热议问题