Best way to sum the values of an object array by property

To sum values of an object array by property, we create a function called sumArray like this:

const sumArray = (arrayToSum, key) => {
  return arrayToSum.reduce((a, b) => a + (b[key] || 0), 0);
};


Then use it to sum by any property of an object array whenever you want:

const fruits = [
  { name: "Apple", amount: 56 },
  { name: "Banana", amount: 20 },
  { name: "Tomato", amount: 25 },
  { name: "Strawberry", amount: 53 }
];
const totalFruits = sumArray(fruits, "amount");
console.log(totalFruits); // 154


javascriptsum object arraysum value property

© 2019 4codev

Created with love by Sil.