Skip to content
Advertisement

Group objects by multiple properties in array then sum up their values

Grouping elements in array by multiple properties is the closest match to my question as it indeed groups objects by multiple keys in an array. Problem is this solution doesn’t sum up the properties value then remove the duplicates, it instead nests all the duplicates in a two-dimensional arrays.

Expected behavior

I have an array of objects which must be grouped by shape and color.

JavaScript

Objects in this array are considered duplicates only if both their shape and color are the same. If they are, I want to respectively sum up their used and instances values then delete the duplicates.

So in this example result array may only contain four combinations : square red, square blue, circle red, circle blue

Problem

I tried a simpler approach here:

JavaScript

but it outputs

JavaScript

instead of expected result:

JavaScript

How can I get my function to properly group the objects by shape and color ? i.e. sum up their values and remove the duplicates ?

Advertisement

Answer

Use Array#reduce with a helper object to group similar objects. For each object, check if the combined shape and color exists in the helper. If it doesn’t, add to the helper using Object#assign to create a copy of the object, and push to the array. If it does, add it’s values to used and instances.

JavaScript

If you can use ES6, you use a Map to collect the values, and then convert it back to an array by spreading the Map#values:

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