I have the following array :
[
{ name: "iPhone 12", quantity: 12, price: 325, … },
{ name: "iPhone 12", quantity: 4, price: 325, … },
{ name: "iPhone 13", quantity: 2, price: 525, … },
{ name: "iPhone 12", quantity: 2, price: 325 },
{ name: "iPhone 13", quantity: 3, price: 525 },
{ name: "iPhone SE", quantity: 2, price: 59 }
]
And I want to sum the quantity properties of each object in order to have an array with distinct elements like this :
[
{ name: "iPhone 12", quantity: 18, price: 325 },
{ name: "iPhone 13", quantity: 5, price: 525 },
{ name: "iPhone SE", quantity: 2, price: 59 }
]
How can I do that?
CodePudding user response:
Seems like a good task for Array.prototype.reduce
const data = [{
name: "iPhone 12",
quantity: 12,
price: 325,
},
{
name: "iPhone 12",
quantity: 4,
price: 325,
},
{
name: "iPhone 13",
quantity: 2,
price: 525,
},
{
name: "iPhone 12",
quantity: 2,
price: 325
},
{
name: "iPhone 13",
quantity: 3,
price: 525
},
]
const summed = data.reduce((sum, current) => {
const item = sum.find(el => el.name === current.name)
if (item) {
for (const key in item) {
if (key === 'name') continue
item[key] = current[key]
}
} else {
sum.push({ ...current })
}
return sum
}, [])
console.log(summed)