Borislav Hadzhiev
Sat Nov 13 2021·2 min read
Photo by Yuri Efremov
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.
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
.
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
.
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.
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:
reduce()
method to iterate over the array.accumulator
value + 1.accumulator
.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
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.