Categories
JavaScript Answers

How to use array reduce with condition in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *