Count Items That Meet a Condition in JavaScript
In this tutorial, we'll walk through three methods to count array items that meet a certain condition. These include using filter()
, reduce()
, and a classic for
loop. Each method is explained step by step with a full code example and output.
Method 1: Using filter()
and length
The filter()
method creates a new array with only the elements that satisfy a condition. You can then use the length
property to count how many items passed the test. This method is both readable and expressive—perfect for most counting needs.
const fruits = ["apple", "banana", "cherry", "date", "fig"];
const countWithA = fruits.filter(fruit => fruit.includes("a")).length;
console.log("Number of fruits containing 'a':", countWithA);
Number of fruits containing 'a': 3
Method 2: Using reduce()
to Accumulate the Count
The reduce()
method is a powerful tool that processes each item in the array and accumulates a result. In this case, the result is a running count. This method is a bit more advanced, but it gives you fine-grained control over the counting logic.
const numbers = [1, 2, 3, 4, 5, 6];
const evenCount = numbers.reduce((acc, num) => {
return num % 2 === 0 ? acc + 1 : acc;
}, 0);
console.log("Count of even numbers:", evenCount);
Count of even numbers: 3
Method 3: Using a for
Loop for Complete Control
The classic for
loop gives you ultimate control over the counting logic. This is helpful when you want to combine multiple conditions or use early exits, though it’s slightly more verbose than the other methods.
const items = ["Item 1", "Item 2", "Item 3", "Item 2", "Item 4"];
let count = 0;
for (let i = 0; i < items.length; i++) {
if (items[i].includes("2")) {
count++;
}
}
console.log("Items containing '2':", count);
Items containing '2': 2
When Should You Use Each Method?
Use filter()
when you want a clear and readable way to count items based on a condition. It’s concise and works in 90% of everyday use cases. Go with reduce()
when you're already working with reduction logic or need to track multiple counts in one pass. Choose a for
loop when your condition is too complex or when readability benefits from traditional iteration.
Comments
Loading comments...