0

I am working with a multi-dimensional array. the following is my array:

let arr = [[1,2,3],[1,2,3],[1,2,3]];

the length of the inner arrays will always be the same.

I want create a function to add all the arrays elements together with their respective elements and create a new array with the result. so my desired output is

result =[3,6,9];
Aswin
  • 1
  • 2

1 Answers1

0

You can use nested for loop for that.

let arr = [[1,2,3],[1,2,3],[1,2,3]];
let res = Array(arr[0].length).fill(0);
for(let i = 0;i<arr[0].length;i++){
  for(let j = 0;j<arr.length;j++){
    res[i] += arr[j][i]
  }
}
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73