Get the element with the highest occurrence in an array

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

    a=['pear', 'apple', 'orange', 'apple'];
    b={};
    max='', maxi=0;
    for(let k of a) {
      if(b[k]) b[k]++; else b[k]=1;
      if(maxi < b[k]) { max=k; maxi=b[k] }
    }
    

提交回复
热议问题