Skip to content
Advertisement

Sum JavaScript object propertyA values with the same object propertyB in an array of objects

How would one take a JavaScript array of objects, such as

JavaScript

and merge duplicate keys by summing the values?

In order to get something like this:

JavaScript

I have tried iterating and adding to a new array, but this didn’t work:

JavaScript

Advertisement

Answer

You should be assigning each object not found to the result with its .key property.

If it is found, then you need to add its .val.

JavaScript

Also, part of the problem was that you were reusing the item variable to reference the value of .key, so you lost reference to the object.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement