Get the element with the highest occurrence in an array

后端 未结 30 1540
野性不改
野性不改 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 12:06

    Try it too, this does not take in account browser version.

    function mode(arr){
    var a = [],b = 0,occurrence;
        for(var i = 0; i < arr.length;i++){
        if(a[arr[i]] != undefined){
            a[arr[i]]++;
        }else{
            a[arr[i]] = 1;
        }
        }
        for(var key in a){
        if(a[key] > b){
            b = a[key];
            occurrence = key;
        }
        }
    return occurrence;
    }
    alert(mode(['segunda','terça','terca','segunda','terça','segunda']));
    

    Please note that this function returns latest occurence in the array when 2 or more entries appear same number of times!

提交回复
热议问题