I was recently asked what was the best way to sum up an array of arrays of numbers by their respective columns. While I’m not the best code golfer, I am rather lazy, so I do have some terse solutions up my sleeve.
// The input data looks like this, // with each nested array having the same shape. const input = [ [1,2,3,4], [2,2,2,2], [0,2,4,6], ] // To show you the power of flex- er, I mean reduce() const result = input.reduce( (acc, curr) => acc.map((x, i) => x + curr[i]) ) console.log(result);
Which prints the result:
[ 3, 6, 9, 12 ]