Get the element with the highest occurrence in an array

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

    As I'm using this function as a quiz for the interviewers, I post my solution:

    const highest = arr => (arr || []).reduce( ( acc, el ) => {
      acc.k[el] = acc.k[el] ? acc.k[el] + 1 : 1
      acc.max = acc.max ? acc.max < acc.k[el] ? el : acc.max : el
      return acc  
    }, { k:{} }).max
    
    const test = [0,1,2,3,4,2,3,1,0,3,2,2,2,3,3,2]
    console.log(highest(test))
    

提交回复
热议问题