Extracting the most duplicate value from an array in JavaScript (with jQuery)

前端 未结 5 1222
不思量自难忘°
不思量自难忘° 2020-12-01 17:26

I have several array to deal with. I need to extract the most duplicate value from each array.

From [3, 7, 7, 7], I need to find the value 7

5条回答
  •  温柔的废话
    2020-12-01 18:25

    Array.prototype.mostFreq=function(){
     var what, a= this.concat(), ax, freq,
     count, max=0, limit= a.length/2;
     while(a.length){
      what= a.shift();
      count=1; 
      while((ax= a.indexOf(what))!= -1){
       a.splice(ax,1); // remove counted items  
       ++count;
      }
      // if any item has more than half the array, quit counting
      if(count> limit) return what; 
      if(count> max){
       freq= what;
       max= count;
      }
     }
     return freq;
    }
    var a=[1,1,2,5,4,2,7,7,1,1,1,3,7,7,3,4,3,7,3,5,6,2,3,1,1,7,7,2,4,3,6,7,6,6]
    alert(a.mostFreq())
    

提交回复
热议问题