3

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!

0

1 Answer 1

4

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))

Sign up to request clarification or add additional context in comments.

4 Comments

what's the meaning of the , a near the end?
I'm making use of the comma operator. It evaluates each of the expressions inside the brackets, and returns the value of the last, which in this case, is the accumulator
@Gibor No problem, you learn something new everyday :P I only learned about it a month or 2 back, it's useful for writing one liners.
Worked perfectly! Just had to turn Object.values(out) into a variable and use it in my table (separate item). Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.