1

I'm using a nested array like this:

const data = [
  [0],
  [2],
  [[1], 3]
  1
]

Is it possible to count all values together. In this example the result should be 7 (0+2+1+3+1). And is it also possible to count how many arrays are used? This would be 5 arrays

user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

8
 const sumUp = array => array.reduce((sum, el) => sum + (Array.isArray(el) ? sumUp(el) : +el), 0);

This uses a recursive approach with reduce.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151