Get the element with the highest occurrence in an array

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

    Here is my solution to this problem but with numbers and using the new 'Set' feature. Its not very performant but i definitely had a lot of fun writing this and it does support multiple maximum values.

    const mode = (arr) => [...new Set(arr)]
      .map((value) => [value, arr.filter((v) => v === value).length])
      .sort((a,b) => a[1]-b[1])
      .reverse()
      .filter((value, i, a) => a.indexOf(value) === i)
      .filter((v, i, a) => v[1] === a[0][1])
      .map((v) => v[0])
    
    mode([1,2,3,3]) // [3]
    mode([1,1,1,1,2,2,2,2,3,3,3]) // [1,2]
    

    By the way do not use this for production this is just an illustration of how you can solve it with ES6 and Array functions only.

提交回复
热议问题