DEV Community

chandra penugonda
chandra penugonda

Posted on

 

Sum all numbers in an array containing nested arrays using recursion

Problem statement

Sum all numbers in an array containing nested arrays.

input: [1,[2,3],[[4]],5]
output: 15

var arraySum = function(array) {
   // start here
};

Enter fullscreen mode Exit fullscreen mode

Solution:


var arraySum = function (array) {
  let sum = 0;
  for (let i = 0; i < array.length; i++) {
    if (Array.isArray(array[i])) sum += arraySum(array[i]);
    else sum += array[i];
  }
  return sum;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!