Categories
JavaScript Answers

How to sum a property value in an array with JavaScript?

Spread the love

To sum a property value in an array with JavaScript, we use the map and reduce methods.

For instance, we write

const traveler = [
  { description: "Senior", amount: 50 },
  { description: "Senior", amount: 50 },
  { description: "Adult", amount: 75 },
  { description: "Child", amount: 35 },
  { description: "Infant", amount: 25 },
];

const sum = traveler
  .map((item) => item.amount)
  .reduce((prev, next) => prev + next);

to call traveler.map with a callback to get the amount property from each entry and put it in the returned array.

And then we call reduce with a callback to sum up the values from the array returned by map.

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 *