Get the element with the highest occurrence in an array

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

    I guess you have two approaches. Both of which have advantages.

    Sort then Count or Loop through and use a hash table to do the counting for you.

    The hashtable is nice because once you are done processing you also have all the distinct elements. If you had millions of items though, the hash table could end up using a lot of memory if the duplication rate is low. The sort, then count approach would have a much more controllable memory footprint.

提交回复
热议问题