Get the element with the highest occurrence in an array

后端 未结 30 1233
野性不改
野性不改 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:47
    const mode = (str) => {
      return str
        .split(' ')
        .reduce((data, key) => {
          let counter = data.map[key] + 1 || 1
          data.map[key] = counter
    
          if (counter > data.counter) {
            data.counter = counter
            data.mode = key
          }
    
          return data
        }, {
          counter: 0,
          mode: null,
          map: {}
        })
        .mode
    }
    
    console.log(mode('the t-rex is the greatest of them all'))
    
    0 讨论(0)
  • 2020-11-22 11:48

    This solution can return multiple elements of an array in case of a tie. For example, an array

    arr = [ 3, 4, 3, 6, 4, ];
    

    has two mode values: 3 and 6.

    Here is the solution.

    function find_mode(arr) {
        var max = 0;
        var maxarr = [];
        var counter = [];
        var maxarr = [];
    
        arr.forEach(function(){
           counter.push(0);
        });
    
        for(var i = 0;i<arr.length;i++){
           for(var j=0;j<arr.length;j++){
                if(arr[i]==arr[j])counter[i]++; 
           }
        } 
    
    
        max=this.arrayMax(counter);   
      
        for(var i = 0;i<arr.length;i++){
             if(counter[i]==max)maxarr.push(arr[i]);
        }
    
        var unique = maxarr.filter( this.onlyUnique );
        return unique;
    
      };
    
    
    function arrayMax(arr) {
          var len = arr.length, max = -Infinity;
          while (len--) {
                  if (arr[len] > max) {
                  max = arr[len];
                  }
          }
      return max;
     };
    
     function onlyUnique(value, index, self) {
           return self.indexOf(value) === index;
     }
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-11-22 11:54

    Time for another solution:

    function getMaxOccurrence(arr) {
        var o = {}, maxCount = 0, maxValue, m;
        for (var i=0, iLen=arr.length; i<iLen; i++) {
            m = arr[i];
    
            if (!o.hasOwnProperty(m)) {
                o[m] = 0;
            }
            ++o[m];
    
            if (o[m] > maxCount) {
                maxCount = o[m];
                maxValue = m;
            }
        }
        return maxValue;
    }
    

    If brevity matters (it doesn't), then:

    function getMaxOccurrence(a) {
        var o = {}, mC = 0, mV, m;
        for (var i=0, iL=a.length; i<iL; i++) {
            m = a[i];
            o.hasOwnProperty(m)? ++o[m] : o[m] = 1;
            if (o[m] > mC) mC = o[m], mV = m;
        }
        return mV;
    }
    

    If non–existent members are to be avoided (e.g. sparse array), an additional hasOwnProperty test is required:

    function getMaxOccurrence(a) {
        var o = {}, mC = 0, mV, m;
        for (var i=0, iL=a.length; i<iL; i++) {
            if (a.hasOwnProperty(i)) {
                m = a[i];
                o.hasOwnProperty(m)? ++o[m] : o[m] = 1;
                if (o[m] > mC) mC = o[m], mV = m;
            }
        }
        return mV;
    }
    
    getMaxOccurrence([,,,,,1,1]); // 1
    

    Other answers here will return undefined.

    0 讨论(0)
  • 2020-11-22 11:54

    You could solve it in O(n) complexity

    var arr = [1,3,54,56,6,6,1,6];
    var obj = {};
    
    /* first convert the array in to object with unique elements and number of times each element is repeated */
    for(var i = 0; i < arr.length; i++)
    {
       var x = arr[i];
       if(!obj[x])
         obj[x] = 1;
       else 
         obj[x]++;
    }
    
    console.log(obj);//just for reference
    
    /* now traverse the object to get the element */
    var index = 0;
    var max = 0;
    
    for(var obIndex in obj)
    {
      if(obj[obIndex] > max)
      {
        max = obj[obIndex];
        index = obIndex;
      }
    }
    console.log(index+" got maximum time repeated, with "+ max +" times" );
    

    Just copy and paste in chrome console to run the above code.

    0 讨论(0)
  • 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 ;)!

    0 讨论(0)
提交回复
热议问题