Get the element with the highest occurrence in an array

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

    For the sake of really easy to read, maintainable code I share this:

    function getMaxOcurrences(arr = []) {
      let item = arr[0];
      let ocurrencesMap = {};
    
      for (let i in arr) {
        const current = arr[i];
    
        if (ocurrencesMap[current]) ocurrencesMap[current]++;
        else ocurrencesMap[current] = 1;
    
        if (ocurrencesMap[item] < ocurrencesMap[current]) item = current;
      }
    
      return { 
        item: item, 
        ocurrences: ocurrencesMap[item]
      };
    }
    

    Hope it helps someone ;)!

提交回复
热议问题