Get the element with the highest occurrence in an array

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

    Here’s the modern version using built-in maps (so it works on more than things that can be converted to unique strings):

    'use strict';
    
    const histogram = iterable => {
        const result = new Map();
    
        for (const x of iterable) {
            result.set(x, (result.get(x) || 0) + 1);
        }
    
        return result;
    };
    
    const mostCommon = iterable => {
        let maxCount = 0;
        let maxKey;
    
        for (const [key, count] of histogram(iterable)) {
            if (count > maxCount) {
                maxCount = count;
                maxKey = key;
            }
        }
    
        return maxKey;
    };
    
    console.log(mostCommon(['pear', 'apple', 'orange', 'apple']));

提交回复
热议问题