Get the element with the highest occurrence in an array

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

    // O(n)
    var arr = [1, 2, 3, 2, 3, 3, 5, 6];
    var duplicates = {};
    max = '';
    maxi = 0;
    arr.forEach((el) => {
        duplicates[el] = duplicates[el] + 1 || 1;
      if (maxi < duplicates[el]) {
        max = el;
        maxi = duplicates[el];
      }
    });
    console.log(max);
    

提交回复
热议问题