Sum an Array of Arrays Using JavaScript or TypeScript
A demonstration of using JavaScript/TypeScript to sum up the columns of a bunch of arrays, without having to write a for-loop or while-loop.
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.
Here’s my quick and dirty solution, using JavaScript’s Reduce:
// 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 ]