Count items satisfying a condition in a JavaScript array
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.
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4, 5]; // count the number of elements that are greater than 3 let count = arr.filter(item => item > 3).length; console.log(count); // 2 |
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.
|
1 2 3 4 5 6 |
let arr = [1, 2, 3, 4, 5]; let count = 0; arr.forEach(item => (item > 3) ? count++: count); console.log(count); // 2 |
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.
|
1 2 3 4 5 6 7 8 9 10 |
let arr = [1, 2, 3, 4, 5]; let count = arr.reduce(function (acc, item) { if (item > 3) { acc++; // Increment the counter } return acc; // Return the updated counter }, 0); // Initialize the counter to zero console.log(count); // 2 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
let arr = [1, 2, 3, 4, 5]; // initialize a counter variable let count = 0; for (let i of arr) { if (i > 3) { // increment the counter by one count++; } } console.log(count); // 2 |
That’s all about counting the number of items in an array that satisfy a certain condition in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)