Leem Leem - 1 month ago 5
Javascript Question

How to count the number of certain element in an array?

If I have an array

[1, 2, 3, 5, 2, 8, 9, 2]
, I would like to check how many
2
s there are in the array. What is the most elegant way to do it in JavaScript without looping with
for
loop?

Answer

Very simple:

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