Get the item that appears the most times in an array

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

    I solved it this way for finding the most common integer

    function mostCommon(arr) {
        // finds the first most common integer, doesn't account for 2 equally common integers (a tie)
    
        freq = [];
    
        // set all frequency counts to 0
        for(i = 0; i < arr[arr.length-1]; i++) {
          freq[i] = 0;
        }
    
        // use index in freq to represent the number, and the value at the index represent the frequency count 
        for(i = 0; i < arr.length; i++) {
          freq[arr[i]]++; 
        }
    
        // find biggest number's index, that's the most frequent integer
        mostCommon = freq[0];
        for(i = 0; i < freq.length; i++) {
          if(freq[i] > mostCommon) {
            mostCommon = i;
          }
        }
    
        return mostCommon;
    } 
    

提交回复
热议问题