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?
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.