Count Elements in Array that match a Condition using JS

avatar

Borislav Hadzhiev

Sat Nov 13 20212 min read

banner

Photo by Yuri Efremov

Count Elements in Array that match a Condition #

Use the filter() method to count the elements in an array that match a condition. On each iteration, check if the condition is met and return true if it is. Access the length property on the returned array to get the count of elements that match the condition.

index.js
const arr = [{id: 1}, {id: 2}, {id: 3}]; const count = arr.filter(obj => { if (obj.id > 1) { return true; } return false; }).length; console.log(count); // ๐Ÿ‘‰๏ธ 2

The function we passed to the Array.filter method gets called with each element in the array.

On each iteration, we check if the id property of the object is greater than 1 and if it is we return true.

The filter method returns a new array containing the elements of the original array for which the callback function returns a truthy value.

In the example, the filter method returns an array containing the 2 objects that have an id property with a value greater than 1.

index.js
const arr = [{id: 1}, {id: 2}, {id: 3}]; // ๐Ÿ‘‡๏ธ [{id: 2}, {id: 3}] console.log(arr.filter(obj => obj.id > 1));

To get the count of the elements that satisfy the condition, we access the length property on the filtered array.

index.js
const arr = [{id: 1}, {id: 2}, {id: 3}]; // ๐Ÿ‘‡๏ธ 2 console.log(arr.filter(obj => obj.id > 1).length);

An alternative approach is to use the Array.reduce method.

To count the elements in an array that match a condition:

  1. Use the reduce() method to iterate over the array.
  2. If the element matches the condition return the accumulator value + 1.
  3. If the condition is not matched, return the accumulator.
index.js
const arr = [{id: 1}, {id: 2}, {id: 3}]; const count = arr.reduce((accumulator, obj) => { if (obj.id > 1) { return accumulator + 1; } return accumulator; }, 0); console.log(count); // ๐Ÿ‘‰๏ธ 2
The function we passed to the reduce() method gets called with each element in the array.

We passed 0 as the initial value for the accumulator variable.

On each iteration, we check if the array element (object) has an id property with a value greater than 1. If the condition is met, we return the value of the accumulator + 1.

The value we return from the callback function gets passed as the accumulator for the next iteration.

After the last iteration, the reduce method returns the count of array elements that match the condition.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee