Get the element with the highest occurrence in an array

后端 未结 30 1555
野性不改
野性不改 2020-11-22 11:17

I\'m looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

[\'pear\', \'a         


        
30条回答
  •  误落风尘
    2020-11-22 11:54

    Time for another solution:

    function getMaxOccurrence(arr) {
        var o = {}, maxCount = 0, maxValue, m;
        for (var i=0, iLen=arr.length; i maxCount) {
                maxCount = o[m];
                maxValue = m;
            }
        }
        return maxValue;
    }
    

    If brevity matters (it doesn't), then:

    function getMaxOccurrence(a) {
        var o = {}, mC = 0, mV, m;
        for (var i=0, iL=a.length; i mC) mC = o[m], mV = m;
        }
        return mV;
    }
    

    If non–existent members are to be avoided (e.g. sparse array), an additional hasOwnProperty test is required:

    function getMaxOccurrence(a) {
        var o = {}, mC = 0, mV, m;
        for (var i=0, iL=a.length; i mC) mC = o[m], mV = m;
            }
        }
        return mV;
    }
    
    getMaxOccurrence([,,,,,1,1]); // 1
    

    Other answers here will return undefined.

提交回复
热议问题