3

I'm looking to sum positions in an object of arrays. Essentially, each number represents a yearly amount for an expense line item, and I need to sum these up for each year. The object looks like this (see below) and the result should be an array which = [1500, 1900, 2400] given the object below.

x = [{
      "HVAC": [100, 200, 300, 400],
      "foundation": [500, 600, 700, 800],
      "roof": [900, 1000, 1100, 1200]
    }];

If the arrays weren't named, and instead looked like:

x = [
          [100, 200, 300, 400],
          [500, 600, 700, 800],
          [900, 1000, 1100, 1200]
        ];

Then this function would do what I want (thanks to this post Sum array of arrays (matrix) vertically efficiently/elegantly):

 $scope.reserveTotals = x.reduce(function(a, b) {
      return a.map(function(v, i) {
        return v + b[i];
      });
    });

As it stands, I need to keep the original structure and am just struggling to adapt that function do what I need. Any help appreciated!

2 Answers 2

3

A slightly different solution.

var x = { "HVAC": [100, 200, 300, 400], "foundation": [500, 600, 700, 800], "roof": [900, 1000, 1100, 1200] },
    result = Object.keys(x).reduce(function (r, k) {
        x[k].forEach(function (a, i) {
            r[i] = (r[i] || 0) + a;
        });
        return r;
    }, []);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

2

You can use for...in loop and reduce

x = [{
  "HVAC": [100, 200, 300, 400],
  "foundation": [500, 600, 700, 800],
  "roof": [900, 1000, 1100, 1200]
}];

for(var p in x[0]) {
  x[0][p] = x[0][p].reduce((a, b) => { return a + b});
}

console.log(x)

Comments

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.