-2

examples:

let a1 = [[1,2,3],[4,5,6]] //-> [5,7,9]
let a2 = [[1,2,3],[4,5,6],[7,8,9]] //-> [12,15,18]
let a3 = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7]] //-> [10,14,18,22]

I thought I can do this easily but now I can't think straight anymore. :-)

thank you.

roumen
  • 7
  • 1
  • 4

1 Answers1

1

You could reduce the array and map new arrays with sums.

const
    add = array => array.reduce((a, b) => a.map((v, i) => v + b[i])),
    a1 = [[1, 2, 3], [4, 5, 6]],
    a2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    a3 = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]];    
     
console.log(...add(a1)); // [5, 7, 9] 
console.log(...add(a2)); // [12, 15, 18]
console.log(...add(a3)); // [10, 14, 18, 22]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • perfect! thank you. I was so close to a similar solution but I screwed up the logic with mapping. – roumen Apr 26 '22 at 21:51