Sum array of arrays (matrix) vertically efficiently/elegantly

后端 未结 5 1027
眼角桃花
眼角桃花 2020-12-17 02:18

In Javascript, if I have an array of arrays representing a matrix, say

x = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]
];

summing it

5条回答
  •  情话喂你
    2020-12-17 02:53

    You could sum the values at the same index.

    Use: array.reduce(sum)

    var sum = (r, a) => r.map((b, i) => a[i] + b);
    
    console.log([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]].reduce(sum));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题