Reduce an array of objects and sum property for each distinct object

后端 未结 1 859
梦毁少年i
梦毁少年i 2021-01-25 18:13

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

相关标签:
1条回答
  • 2021-01-25 19:01

    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);
    
    0 讨论(0)
提交回复
热议问题