I am not sure for what functions I should look at to achieve what I am trying to do. Probably reduce is not correct.
A database query returns a list of objects like this
First function reduces 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);