0

I have the following array like this

[
 {name: "calpol", quantity: 12},
 {name: "paracetamol", quantity: 15},
 {name: "paracetamol", quantity: 10},
]

and I want to sum up the quantity when the product is the same so i can get an array like :

[
 {name: "calpol", quantity: 12},
 {name: "paracetamol", quantity: 25},
]
hamdi islam
  • 1,327
  • 14
  • 26

1 Answers1

2

Use reduce and in the accumulator array check if there exist a object with a name such as calpol or paracetamol. If it exist then update the quantity else create new object and push it in the accumulator

let prod = [{
    name: "calpol",
    quantity: 12
  },
  {
    name: "paracetamol",
    quantity: 15
  },
  {
    name: "paracetamol",
    quantity: 10
  },
]

let sum = prod.reduce(function(acc, curr) {
  let findIndex = acc.findIndex(item => item.name === curr.name);

  if (findIndex === -1) {
    acc.push(curr)
  } else {

    acc[findIndex].quantity += curr.quantity
  }
  return acc;
}, [])

console.log(sum)
brk
  • 48,835
  • 10
  • 56
  • 78