简体   繁体   English

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

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

So I'm trying to figure out how to generate an associative array that lists the elements of an array, and the number of times each element occurs, without knowing what the elements are beforehand. 所以我试图弄清楚如何生成一个关联数组,列出数组的元素,以及每个元素出现的次数,而不事先知道元素是什么。

As an example, let's say I have an array of animals: var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino'] 举个例子,假设我有一系列动物: var animals = ['Rhino', 'Lion', 'Dog', 'Parrot', 'Parrot', 'Cat', 'Zebra', 'Rhino']

I'd like to generate an object that ultimately looks like: 我想生成一个最终看起来像的对象:

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

If I knew what the animals in the array were beforehand, I could of course do something like: 如果我事先知道阵列中的动物是什么,我当然可以这样做:

var animalsCount = {};

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

animalsCount['Rhino'] = numberOfRhinos

to get an object like I'd like. 得到一个像我想要的对象。 The problem of course is that this becomes quite lengthy and repetitive depending on the number of animals. 问题当然是根据动物的数量,这变得非常冗长和重复。 As well, if I don't know what each type of animal is I can't create the object this way. 同样,如果我不知道每种动物是什么,我就不能用这种方式创造物体。 There must be a way to do this without knowing that information, but I'm stuck. 必须有一种方法可以在不知道这些信息的情况下做到这一点,但我被困住了。

Easiest way is to create a map, initializing (to 1) values in the array as aa property on that map. 最简单的方法是创建一个地图,将数组中的值初始化为(1)作为该地图上的属性。 You can increment a property's value every time you see a property that is not undefined. 每次看到未定义的属性时,都可以增加属性的值。

  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 */ 

Just generate a dictionary by looping trough the animals, then fill it looping through your animals again. 只需通过循环动物生成一本字典,然后将它再次循环通过你的动物。

  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)) 

Just loop over the array elements with properties and store them in the object. 只需使用属性循环遍历数组元素并将它们存储在对象中。

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

You can iterate over each element in the array, create a key in the counting object (associative arrays are called just called objects in JS) if one does not exists and set it to 1, or if it does exists add to the value. 您可以迭代数组中的每个元素,在计数对象中创建一个键(关联数组在JS中称为刚被调用的对象),如果一个不存在并将其设置为1,或者它确实存在则添加到该值。

animals.forEach(function(animal){
  var count;

  count = animalsCount[animal];

  if (count){
    animalsCount[animal] = count + 1;
  } else {
    animalsCount[animal] = 1;
  }  
})

You can easily get it in two arrays as below. 你可以轻松地将它放在两个数组中,如下所示。

 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)); 

Disclaimer : output array is alphabetically sorted. 免责声明:输出数组按字母顺序排序。

The countBy in the underscore may meet your requirement. 下划线中countBy可能符合您的要求。

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

output: 输出:

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

You can use library like lodash to get this result. 您可以使用像lodash这样的库来获得此结果。

Otherwise you can iterate your array. 否则你可以迭代你的数组。 Check if your animalsCount prototype contains the animal entry and increment or initialize value. 检查animalsCount原型是否包含动物条目并增加或初始化值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM