CodePark/ problems / Sum a Nested Array
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Foundations

Sum a Nested Array

easyabout 10 minutes in an interview

Write sumNested(items) that adds up every number inside items, no matter how deeply the arrays are nested.

  • Each element of items is either a number or another array of the same shape.
  • Empty arrays add nothing. An empty items returns 0.
  • Numbers can be negative.
  • Don't use .flat() or JSON.stringify. Handle the nesting yourself: sumNested should call itself on the inner arrays.
Input: items = [1, [2, 3], [[4]]] Output: 10
Input: items = [5, [], [-2, [1, [1]]]] Output: 5
Input: items = [] Output: 0