javascript

Array reducce

sum an array of objects

//Reference ->  https://sebhastian.com/javascript-sum-array-objects/
//Sometimes, you need to count the sum of property in an array of objects. 
//For example, you may find an array of items, and you want to sum the total quantity a person must pay for the items
let cart = [
  {
    name: "JavaScript book",
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    price: 9,
  },
];
// totalPrice is 92
let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.price;
}, 0);


//Perform multiple operations before returning the data
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 215

let totalPrice = cart.reduce(function (accumulator, item) {
  return accumulator + item.quantity * item.price;
}, 0);



//Filter the array before reduce
let cart = [
  {
    name: "JavaScript book",
    quantity: 3,
    price: 4,
  },
  {
    name: "UGG Women's Hazel Ankle Boot",
    quantity: 2,
    price: 79,
  },
  {
    name: "OXO Good Grips 11-Inch Balloon Whisk",
    quantity: 5,
    price: 9,
  },
];

// totalPrice is 170

let totalPrice = cart
  .filter(
    (item) =>
      item.name === "JavaScript book" ||
      item.name === "UGG Women's Hazel Ankle Boot"
  )
  .reduce((accumulator, item) => {
    return accumulator + item.quantity * item.price;
  }, 0);
Was this helpful?