Get the element with the highest occurrence in an array

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

    As I'm using this function as a quiz for the interviewers, I post my solution:

    const highest = arr => (arr || []).reduce( ( acc, el ) => {
      acc.k[el] = acc.k[el] ? acc.k[el] + 1 : 1
      acc.max = acc.max ? acc.max < acc.k[el] ? el : acc.max : el
      return acc  
    }, { k:{} }).max
    
    const test = [0,1,2,3,4,2,3,1,0,3,2,2,2,3,3,2]
    console.log(highest(test))
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 12:03
    var array = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17],
        c = {}, // counters
        s = []; // sortable array
    
    for (var i=0; i<array.length; i++) {
        c[array[i]] = c[array[i]] || 0; // initialize
        c[array[i]]++;
    } // count occurrences
    
    for (var key in c) {
        s.push([key, c[key]])
    } // build sortable array from counters
    
    s.sort(function(a, b) {return b[1]-a[1];});
    
    var firstMode = s[0][0];
    console.log(firstMode);
    
    0 讨论(0)
  • 2020-11-22 12:03
    var cats = ['Tom','Fluffy','Tom','Bella','Chloe','Tom','Chloe'];
    var counts = {};
    var compare = 0;
    var mostFrequent;
    (function(array){
       for(var i = 0, len = array.length; i < len; i++){
           var word = array[i];
    
           if(counts[word] === undefined){
               counts[word] = 1;
           }else{
               counts[word] = counts[word] + 1;
           }
           if(counts[word] > compare){
                 compare = counts[word];
                 mostFrequent = cats[i];
           }
        }
      return mostFrequent;
    })(cats);
    
    0 讨论(0)
  • 2020-11-22 12:04
    function mode(arr){
      return arr.reduce(function(counts,key){
        var curCount = (counts[key+''] || 0) + 1;
        counts[key+''] = curCount;
        if (curCount > counts.max) { counts.max = curCount; counts.mode = key; }
        return counts;
      }, {max:0, mode: null}).mode
    }
    
    0 讨论(0)
  • 2020-11-22 12:04

    Here’s the modern version using built-in maps (so it works on more than things that can be converted to unique strings):

    'use strict';
    
    const histogram = iterable => {
        const result = new Map();
    
        for (const x of iterable) {
            result.set(x, (result.get(x) || 0) + 1);
        }
    
        return result;
    };
    
    const mostCommon = iterable => {
        let maxCount = 0;
        let maxKey;
    
        for (const [key, count] of histogram(iterable)) {
            if (count > maxCount) {
                maxCount = count;
                maxKey = key;
            }
        }
    
        return maxKey;
    };
    
    console.log(mostCommon(['pear', 'apple', 'orange', 'apple']));

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