Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']

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.

like image 577
hmlee Avatar asked Nov 11 '15 18:11

hmlee


People also ask

How do you count the number of elements in an array?

Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof() . int numArrElements = sizeof(myArray) / sizeof(int);

How do you count elements in an array with conditions?

To count the elements in an array that match a condition: Use the filter() method to iterate over the array. On each iteration, check if the condition is met. Access the length property on the array to get the number of elements that match the condition.


1 Answers

Easiest way is to create a map, initializing (to 1) values in the array as a a property on that map. 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
    */
like image 80
Juan Mendes Avatar answered Oct 06 '22 07:10

Juan Mendes