Reputation: 73
I need to take an array and combine any objects with the same key and add the values together to create a single object (if the keys match).
Here's an example of the array I have:
var arr = [
{type: "2 shlf cart", itemCount: 4},
{type: "2 shlf cart", itemCount: 4},
{type: "5 shlf cart", itemCount: 10}
]
What I need is:
var arr = [
{type: "2 shlf cart", itemCount: 8},
{type: "5 shlf cart", itemCount: 10}
]
I was able to use reduce and map in a different scenario where I needed a count but not where I needed to combine the keys.
I searched for an answer that matches my specific question but couldn't find anything so apologies if this is a duplicate. The question was similar on a lot of posts but in most cases they needed to count objects with the same key, value pair rather than actually add the values with the same keys.
Thank you!
Upvotes: 3
Views: 397
Reputation: 6456
You can use reduce
and Object.values
for a single line solution:
const arr = [
{type: "2 shlf cart", itemCount: 4},
{type: "2 shlf cart", itemCount: 4},
{type: "5 shlf cart", itemCount: 10}
]
const out = arr.reduce((a, o) => (a[o.type] ? a[o.type].itemCount += o.itemCount : a[o.type] = o, a), {})
console.log(Object.values(out))
Of course, if this looks too complicated, you can always write it out for readability:
const arr = [
{type: "2 shlf cart", itemCount: 4},
{type: "2 shlf cart", itemCount: 4},
{type: "5 shlf cart", itemCount: 10}
]
const out = arr.reduce((a, o) => {
if (a[o.type]) {
a[o.type].itemCount += o.itemCount
} else {
a[o.type] = o
}
return a
}, {})
console.log(Object.values(out))
Upvotes: 4