Get the element with the highest occurrence in an array

后端 未结 30 1542
野性不改
野性不改 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 11:56

    With ES6, you can chain the method like this:

        function findMostFrequent(arr) {
          return arr
            .reduce((acc, cur, ind, arr) => {
              if (arr.indexOf(cur) === ind) {
                return [...acc, [cur, 1]];
              } else {
                acc[acc.indexOf(acc.find(e => e[0] === cur))] = [
                  cur,
                  acc[acc.indexOf(acc.find(e => e[0] === cur))][1] + 1
                ];
                return acc;
              }
            }, [])
            .sort((a, b) => b[1] - a[1])
            .filter((cur, ind, arr) => cur[1] === arr[0][1])
            .map(cur => cur[0]);
        }
        
        console.log(findMostFrequent(['pear', 'apple', 'orange', 'apple']));
        console.log(findMostFrequent(['pear', 'apple', 'orange', 'apple', 'pear']));

    If two elements have the same occurrence, it will return both of them. And it works with any type of element.

提交回复
热议问题