Get the item that appears the most times in an array

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

提交回复
热议问题