Javascript. How to count the number of specific elements in an array

Sometime we need to count, how many elements there are in an array of Javascript, but specific elements, for example if you have an array like this:

[1, 2, 3, 5, 2, 8, 9, 2]

Then you need to know how many elements there are of the number 2, the easy form maybe can be, if you create a cycle to count each one elements and writing a conditional with the element to compare if exists or not, look this:

var count = 0;
for(var i = 0; i < array.length; ++i){
    if(array[i] == 2)
        count++;
}

If you want beautify this, maybe you can create a method with parameters, something like this:

function countEelements(element,array)
{
var count = 0;
for(var i = 0; i < array.length; ++i){
    if(array[i] == element)
        count++;
}
return count;
}

that is better, but in Javascript exists a method called filter in the arrays.

The explanation is:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Then if you write something like this:

var count = array.filter(function(x){return x==2}).length

You will get the total of elements of an array, that is very easy.

 

Leave a Reply