Reduce An Array Of Objects And Sum Property For Each Distinct Object
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 one: resul
Solution 1:
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}
];
(functiongroupSum(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: {}});
returnArray.from(newSet(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);
Post a Comment for "Reduce An Array Of Objects And Sum Property For Each Distinct Object"