Categories
JavaScript Answers

How to use array reduce with condition in JavaScript?

Spread the love

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.

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 *