This post will discuss how to count the number of items in an array that satisfy a certain condition in JavaScript.

There are several ways to count the number of items in an array that satisfy a certain condition in JavaScript. Here are some of the methods that we can use, along with some examples:

1. Using filter() function

The Array.filter() function creates a new array that contains only the elements that pass a test function. This test function checks if the current element satisfies the condition. Then, it accesses the length property of the new array to get the number of elements that match the condition.

Download  Run Code

2. Using forEach() function

The forEach() function allows us to iterate over each element of the array and perform an operation. We can use it to count the number of items in the array that satisfy a condition using the callback function and ternary operator.

Download  Run Code

3. Using reduce() function

The reduce() function applies a function to each element of the array, accumulating the result in a single value. The function can use a counter variable to increment it by one if the current element satisfies the condition. Then, it returns the final value of the counter as the result. This function is simple and elegant, but it requires ES6 support or a polyfill for older browsers.

Download  Run Code

4. Using a loop

This is another way to get the number of items in an array that satisfy a condition, but it is less concise and less preferred than the above discussed options. The idea is to use a loop to iterate over the array elements and increment a counter variable by one if the current element satisfies the condition. This function is compatible with older browsers, but it may not be very efficient or elegant for large arrays.

Download  Run Code

That’s all about counting the number of items in an array that satisfy a certain condition in JavaScript.