0

I have searched for similar questions on here but the expected result does not meet my needs. Consider the following multidimensional array.

let list = [
   [1,   10,    13,    4],
   [5,   6,    83,    45],
   [9,   18,   11,   12]
];

How would you go about merging all values to produce the following result.

const output = [15, 34, 107, 61];
John Doe
  • 65
  • 1
  • 11

1 Answers1

3

You could reduce the array by adding up the numbers:

 list.reduce((a, b) => a.map((n, i) => n + b[i]))

(This will fail if the arrays got different lengths)

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • The good news is that it works, could you give a brief explanation so I can understand why it works? – John Doe Jul 25 '18 at 12:42
  • @jermaine you should read about reduce first, MDN has a good explanation, also [this answer](https://stackoverflow.com/questions/50245957/sorting-array-with-javascript-reduce-function/50246094#50246094) might help – Jonas Wilms Jul 25 '18 at 12:46