DEV Community

chandra penugonda
chandra penugonda

Posted on

1 2

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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay