Get the element with the highest occurrence in an array

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

    Based on Emissary's ES6+ answer, you could use Array.prototype.reduce to do your comparison (as opposed to sorting, popping and potentially mutating your array), which I think looks quite slick.

    const mode = (myArray) =>
      myArray.reduce(
        (a,b,i,arr)=>
         (arr.filter(v=>v===a).length>=arr.filter(v=>v===b).length?a:b),
        null)
    

    I'm defaulting to null, which won't always give you a truthful response if null is a possible option you're filtering for, maybe that could be an optional second argument

    The downside, as with various other solutions, is that it doesn't handle 'draw states', but this could still be achieved with a slightly more involved reduce function.

提交回复
热议问题