Sometimes, we want to use array reduce with condition in JavaScript.
In this article, we’ll look at how to use array reduce with condition in JavaScript.
How to use array reduce with condition in JavaScript?
To use array reduce with condition in JavaScript, we can use the array filter
method to return an array with the filtered entries before we call reduce
.
For instance, we write
records
.filter(({ gender }) => gender === "GIRLS")
.reduce((sum, record) => sum + record.value);
to call filter
to return the items with the gender
property set to 'GIRLS
‘.
Then we call reduce
to sum up the value
property of each entry.
Conclusion
To use array reduce with condition in JavaScript, we can use the array filter
method to return an array with the filtered entries before we call reduce
.