Categories
JavaScript Answers

How to Count Certain Elements in a JavaScript Array?

Spread the love

Sometimes, we may want to count certain elements in a JavaScript array.

In this article, we’ll look at how to count certain elements in a JavaScript array.

Using the Array.prototype.filter Method

The Array.prototype.filter method lets us return an array with the items that meets the condition we’re looking for.

Therefore, we can use the length property of the array returned by filter to count the elements that meet the given condition.

For instance, we can write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.filter(x => x % 2 === 0).length
console.log(numEvens)

We have the arr with some numbers.

To count all the even numbers in the array, we can use the filter method with the callback that returns x % 2 === 0 to return an array that meets this condition, which are even numbers.

Then we can use the length property to get the number of entries in the array.

So we have numEvens equal 4 as seen from the console log.

Using the Array.prototype.reduce Method

Also, we can use the Array.prototype.reduce method to count the number of items that meet the given condition.

To count the number of even numbers with reduce , we write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.reduce((total, x) => (x % 2 === 0 ? total + 1 : total), 0)
console.log(numEvens)

We call reduce with a callback that takes the total and x parameters.

total is the total returned so far, and x is the value being iterated through to compute the total .

We return total + 1 if x % 2 is 0 and total otherwise.

0 in the 2nd argument is the initial value of total .

Therefore, we should get the same value for numEvens as before.

Conclusion

We can count certain elements in an array with the array instances filter or reduce methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *