Reduce the array of objects and the sum property for each individual object

I'm not sure what features I should look for in order to achieve what I'm trying to do. Probably the reduction is wrong.

A database query returns a list of objects such as this:

result = [{group1: 'A', group2: 'A', SUM: 5}, {group1: 'A', group2: 'B', SUM: 2}, {group1: 'C', groupe2: 'B', SUM: 3} ] 

I want to "reduce" or "group" this array to get an object for each individual value of group1 and group2 and its relative SUM value like this object below:

 wanted = [{group1: 'A', group1_SUM: 7, group2: 'A', group2_SUM: 5}, {group1: 'B', group1_SUM: 0, group2: 'B', group2_SUM: 5}, {group1: 'C', group1_SUM: 3, group2: 'C', group2_SUM: 0} ] 

It can also be:

 wanted = [{groupName: 'A', group1_SUM: 7, group2_SUM: 5}, {groupName: 'B', group1_SUM: 0, group2_SUM: 5}, {groupName: 'C', group1_SUM: 3, group2_SUM: 0} ] 
+1
source share
1 answer

The first function reduces the result to find the sums for each group.

Then we go through each group to return the results.

 var result = [{group1: 'A', group2: 'A', SUM: 5}, {group1: 'A', group2: 'B', SUM: 2}, {group1: 'C', group2: 'B', SUM: 3} ]; (function groupSum(result) { var sums = result.reduce(function(a, e) { a.group1_SUM[e.group1] = (a.group1_SUM[e.group1] || 0) + e.SUM; a.group2_SUM[e.group2] = (a.group2_SUM[e.group2] || 0) + e.SUM; return a; }, {group1_SUM: {}, group2_SUM: {}}); return Array.from(new Set(Object.keys(sums.group1_SUM).concat(Object.keys(sums.group2_SUM)))).map(function(e) { return { groupName: e, group1_SUM: sums.group1_SUM[e] || 0, group2_SUM: sums.group2_SUM[e] || 0 } }); })(result); 
+2
source

All Articles