0

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.

3 Answers 3

3

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

Comments

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

Comments

1

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.

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.