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 call filter
before we call reduce
.
For instance, write:
const records = [{
value: 24,
gender: "male"
},
{
value: 42,
gender: "female"
},
{
value: 85,
gender: "female"
},
{
value: 12,
gender: "female"
},
{
value: 10,
gender: "male"
}
]
const sumMaleAge = records
.filter(({
gender
}) => gender === 'male')
.reduce((sum, record) => sum + record.value, 0)
console.log(sumMaleAge)
We call records.filter
with a callback that returns an array with records
entries that have the gender
value set to 'male'
.
Then we call reduce
on the returned array with a callback that returns the sum of the of the value
from the filtered records
entries.
Therefore, sumMaleAge
is 34 since we summed up the value
property values from the records
entries with gender
set to 'male'
.
Conclusion
To use array reduce with condition in JavaScript, we can call filter
before we call reduce
.