Get the element with the highest occurrence in an array

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

    Trying out a declarative approach here. This solution builds an object to tally up the occurrences of each word. Then filters the object down to an array by comparing the total occurrences of each word to the highest value found in the object.

    const arr = ['hello', 'world', 'hello', 'again'];
    
    const tally = (acc, x) => { 
    
      if (! acc[x]) { 
        acc[x] = 1;
        return acc;
      } 
    
      acc[x] += 1;
      return acc;
    };
    
    const totals = arr.reduce(tally, {});
    
    const keys = Object.keys(totals);
    
    const values = keys.map(x => totals[x]);
    
    const results = keys.filter(x => totals[x] === Math.max(...values));
    

提交回复
热议问题