Counting the occurrences / frequency of array elements

前端 未结 30 2057
甜味超标
甜味超标 2020-11-21 06:47

In Javascript, I\'m trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each

相关标签:
30条回答
  • 2020-11-21 07:28

    Check out the code below.

    <html>
    <head>
    <script>
    // array with values
    var ar = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    
    var Unique = []; // we'll store a list of unique values in here
    var Counts = []; // we'll store the number of occurances in here
    
    for(var i in ar)
    {
        var Index = ar[i];
        Unique[Index] = ar[i];
        if(typeof(Counts[Index])=='undefined')  
            Counts[Index]=1;
        else
            Counts[Index]++;
    }
    
    // remove empty items
    Unique = Unique.filter(function(){ return true});
    Counts = Counts.filter(function(){ return true});
    
    alert(ar.join(','));
    alert(Unique.join(','));
    alert(Counts.join(','));
    
    var a=[];
    
    for(var i=0; i<Unique.length; i++)
    {
        a.push(Unique[i] + ':' + Counts[i] + 'x');
    }
    alert(a.join(', '));
    
    </script>
    </head>
    <body>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-21 07:29

    Try this:

    Array.prototype.getItemCount = function(item) {
        var counts = {};
        for(var i = 0; i< this.length; i++) {
            var num = this[i];
            counts[num] = counts[num] ? counts[num]+1 : 1;
        }
        return counts[item] || 0;
    }
    
    0 讨论(0)
  • 2020-11-21 07:30

    If using underscore or lodash, this is the simplest thing to do:

    _.countBy(array);
    

    Such that:

    _.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
    => Object {2: 5, 4: 1, 5: 3, 9: 1}
    

    As pointed out by others, you can then execute the _.keys() and _.values() functions on the result to get just the unique numbers, and their occurrences, respectively. But in my experience, the original object is much easier to deal with.

    0 讨论(0)
  • 2020-11-21 07:31

    If you are using underscore you can go the functional route

    a = ['foo', 'foo', 'bar'];
    
    var results = _.reduce(a,function(counts,key){ counts[key]++; return counts },
                      _.object( _.map( _.uniq(a), function(key) { return [key, 0] })))
    

    so your first array is

    _.keys(results)
    

    and the second array is

    _.values(results)
    

    most of this will default to native javascript functions if they are available

    demo : http://jsfiddle.net/dAaUU/

    0 讨论(0)
  • 2020-11-21 07:31

    Solution using a map with O(n) time complexity.

    var arr = [2, 2, 2, 2, 2, 4, 5, 5, 5, 9];
    
    const countOccurrences = (arr) => {
        const map = {};
        for ( var i = 0; i < arr.length; i++ ) {
            map[arr[i]] = ~~map[arr[i]] + 1;
        }
        return map;
    }
    

    Demo: http://jsfiddle.net/simevidas/bnACW/

    0 讨论(0)
  • 2020-11-21 07:33

    You can use an object to hold the results:

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
    var counts = {};
    
    for (var i = 0; i < arr.length; i++) {
      var num = arr[i];
      counts[num] = counts[num] ? counts[num] + 1 : 1;
    }
    
    console.log(counts[5], counts[2], counts[9], counts[4]);

    So, now your counts object can tell you what the count is for a particular number:

    console.log(counts[5]); // logs '3'
    

    If you want to get an array of members, just use the keys() functions

    keys(counts); // returns ["5", "2", "9", "4"]
    
    0 讨论(0)
提交回复
热议问题