1

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:

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 obtain an object for each distinct group1 and group2 values and the SUM relative of it 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}
         ]

or could 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}
         ]
3
  • One way would be to create a new array, loop over result and push the unique groups into that array. updating the sums as you do so. Commented Sep 18, 2015 at 19:05
  • What specific part of this problem are you having trouble with? What does your code currently look like, and how is it failing? Commented Sep 18, 2015 at 19:09
  • @BelowtheRadar, what you're trying to do is not even clear. Commented Sep 18, 2015 at 19:12

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@BelowtheRadar copy and paste the entire snippet into your console. returns an array of 3 objects, just the way you asked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.