Counting the occurrences / frequency of array elements

前端 未结 30 2062
甜味超标
甜味超标 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:37

    You can simplify this a bit by extending your arrays with a count function. It works similar to Ruby’s Array#count, if you’re familiar with it.

    Array.prototype.count = function(obj){
      var count = this.length;
      if(typeof(obj) !== "undefined"){
        var array = this.slice(0), count = 0; // clone array and reset count
        for(i = 0; i < array.length; i++){
          if(array[i] == obj){ count++ }
        }
      }
      return count;
    }
    

    Usage:

    let array = ['a', 'b', 'd', 'a', 'c'];
    array.count('a'); // => 2
    array.count('b'); // => 1
    array.count('e'); // => 0
    array.count(); // => 5
    

    Gist


    Edit

    You can then get your first array, with each occurred item, using Array#filter:

    let occurred = [];
    array.filter(function(item) {
      if (!occurred.includes(item)) {
        occurred.push(item);
        return true;
      }
    }); // => ["a", "b", "d", "c"]
    

    And your second array, with the number of occurrences, using Array#count into Array#map:

    occurred.map(array.count.bind(array)); // => [2, 1, 1, 1]
    

    Alternatively, if order is irrelevant, you can just return it as a key-value pair:

    let occurrences = {}
    occurred.forEach(function(item) { occurrences[item] = array.count(item) });
    occurences; // => {2: 5, 4: 1, 5: 3, 9: 1}
    

提交回复
热议问题