Get the element with the highest occurrence in an array

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

    Here is another ES6 way of doing it with O(n) complexity

    const result = Object.entries(
        ['pear', 'apple', 'orange', 'apple'].reduce((previous, current) => {
            if (previous[current] === undefined) previous[current] = 1;
            else previous[current]++;
            return previous;
        }, {})).reduce((previous, current) => (current[1] >= previous[1] ? current : previous))[0];
    console.log("Max value : " + result);
    

提交回复
热议问题