To use array reduce with condition in JavaScript, we call filter
to return a filtered array.
For instance, we write
const sum = records
.filter(({ gender }) => gender === "male")
.reduce((sum, record) => sum + record.value);
to call recorda.filter
to return an array where the gender
property in the object in the array is 'male'
.
Then we call reduce
with a callback to return the sum of the partial sum sum
and record.value
.