Get the element with the highest occurrence in an array

后端 未结 30 1537
野性不改
野性不改 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:55

    function mode(array){
        var set = Array.from(new Set(array));
        var counts = set.map(a=>array.filter(b=>b==a).length);
        var indices = counts.map((a,b)=>Math.max(...counts)===a?b:0).filter(b=>b!==0);
        var mode = indices.map(a=>set[a]);
        return mode;
    }
    

提交回复
热议问题