get most occurring elements in array JavaScript

前端 未结 3 1898
借酒劲吻你
借酒劲吻你 2021-01-14 14:27

I have an array that I want to get the most occurring elements,

First scenario

let arr1 = [\'foo\', \'foo\', \'foo\', \         


        
3条回答
  •  不要未来只要你来
    2021-01-14 15:15

    You can count the items with reduce and find the maximum occurring count. Then you can filter any keys that have that count:

    let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];
    
    let counts = arr.reduce((a, c) => {
      a[c] = (a[c] || 0) + 1;
      return a;
    }, {});
    let maxCount = Math.max(...Object.values(counts));
    let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);
    
    console.log(mostFrequent);

提交回复
热议问题