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)