当元素未知时,如何获取数组中元素的计数

How to get count of elements in an array, when elements are unknown

本文关键字:元素 数组 获取 未知 何获取      更新时间:2023-09-26

因此,我试图弄清楚如何生成一个关联数组,该数组列出了数组的元素,以及每个元素出现的次数,而不需要事先知道元素是什么。

举个例子,假设我有一组动物:var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino']

我想生成一个最终看起来像的对象

{ 'Rhino': 2, 'Lion': 1, 'Dog': 1, 'Parrot': 2, 'Cat': 1, 'Zebra': 1 }

如果我事先知道阵列中的动物是什么,我当然可以做一些类似的事情:

var animalsCount = {};
var numberOfRhinos = animals.filter(function(animal) {
   return animal == 'Rhino'
}).length;
animalsCount['Rhino'] = numberOfRhinos

得到我想要的东西。当然,问题是,根据动物的数量,这会变得相当冗长和重复。同样,如果我不知道每种动物是什么,我就不能用这种方式创建对象。在不知道这些信息的情况下,一定有办法做到这一点,但我陷入了困境。

最简单的方法是创建一个映射,将数组中的值初始化(为1)为该映射上的一个属性。每次看到未定义的特性时,都可以增加特性的值。

    function countObjs(arr) {
      // So the object doesn't inherit from Object.prototype and avoids property
      // name collisions
      var obj = Object.create(null);
      arr.forEach(function(item) {
        if (obj[item]) {
          obj[item]++;
        } else {
          obj[item] = 1;
        }
      });
      return obj;
    }
    var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'];
    console.log(countObjs(animals));
    /*
    Cat: 1
    Dog: 1
    Lion: 1
    Parrot: 2
    Rhino: 2
    Zebra: 1
    */

只需通过循环动物来生成一个字典,然后再次循环动物来填充它。

    var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'];
    var animals_dict={};
    for(var i=0;i<animals.length;i++){
        animals_dict[animals[i]]=0;
    }
    for(var i=0;i<animals.length;i++){
      animals_dict[animals[i]]=animals_dict[animals[i]]+1;
    }
    alert(JSON.stringify(animals_dict))

只需在具有属性的数组元素上循环,并将它们存储在对象中。

var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot','Cat', 'Zebra', 'Rhino'];
var animalsCount = {};
for(var i = animals.length - 1; i >=0; i--) {
    var count = animalsCount[animals[i]];
   if(!count) count = 1;
   else count++; 
   animalsCount[animals[i]] = count;
}
console.log(animalsCount); 
//Outupt {Rhino: 2, Zebra: 1, Cat: 1, Parrot: 2, Dog: 1…}
//accessing particular animal count
animalsCount['Cat'];                 //outputs 1

您可以迭代数组中的每个元素,在计数对象中创建一个键(关联数组在JS中称为对象),如果不存在,则将其设置为1,或者如果存在,则添加值。

animals.forEach(function(animal){
  var count;
  count = animalsCount[animal];
  if (count){
    animalsCount[animal] = count + 1;
  } else {
    animalsCount[animal] = 1;
  }  
})

下划线中的countBy可能满足您的要求。

_.countBy(animals, function(n) { return n; })

输出:

{ 'Rhino': 2, 'Lion': 1, 'Dog': 1, 'Parrot': 2, 'Cat': 1, 'Zebra': 1 }

您可以在下面的两个数组中轻松获得它。

var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'];
function foo(arr) {
    var a = [],
        b = [],
        prev;
    arr.sort();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== prev) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length - 1]++;
        }
        prev = arr[i];
    }
    return [a, b];
}
console.log(foo(animals));

免责声明:输出数组按字母顺序排序

您可以使用类似lodash的库来获得此结果。

否则,您可以迭代您的数组。检查您的animalsCount原型是否包含动物条目以及增量或初始化值。