Hung-Yi’s Journal

Front-end Developer, Emacs Adventurer, Home Cook

07 May 2021

Sum an Array of Arrays Using JavaScript or TypeScript

I was recently asked what was the best way to sum up an array of arrays of numbers. 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: A Swiss Army Knife for Arrays:

// 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 ]