DC1
DC1

Reputation: 74

How to add array of arrays in javascript

I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:

var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
  for ( var j = 0; j < a[i].length; j++) {
    console.log(a[i][i] = a[i][j]+a[j][i]);
  }
}

I am trying to obtain the following result:

console.log(a); // -> [7,12,66]

Any suggestions or pin points where I can look for examples of similar things would be appreciated.

Upvotes: 0

Views: 58

Answers (3)

dthree
dthree

Reputation: 20730

From dc2 to dc1, try this:

var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
  for ( var j = 0; j < a[i].length; j++){
    x[j] = x[j] || 0;
    x[j] = x[j] + a[i][j];
  }
}

This worked in testing, and doesn't error with different array lengths.

Upvotes: 1

Matt
Matt

Reputation: 20776

a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]

Upvotes: 1

gefei
gefei

Reputation: 19766

assuming the elements of a has the same length, the following should work

var x=[];
for(var i=0; i<a[0].length; i++){
  var s = 0;  
  for(var j=0; j<a.length; j++){
      s += a[j][i];
  }
  x.push(s);
}

Upvotes: 3

Related Questions