Get the item that appears the most times in an array

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

    If the array contains strings try this solution

        function GetMaxFrequency (array) {
        var store = array;
        var frequency = [];  // array of frequency.
        var result;   // holds the max frequency element.
    
        for(var v in store) {
            var target = store[v];
            var numOccurences = $.grep(store, function (elem) {
            return elem === target;
            }).length;
            frequency.push(numOccurences);
    
        }
        maxValue = Math.max.apply(this, frequency);
        result = store[$.inArray(maxValue,frequency)];
        return result;
    }
    var store = ['ff','cc','cc','ff','ff','ff','ff','ff','ff','yahya','yahya','cc','yahya'];
    alert(GetMaxFrequency(store));
    

提交回复
热议问题