How to sum all elements in a nested array? JavaScript


Let’s say, we are supposed to write a function that takes in a nested array of Numbers and returns the sum of all the numbers. We are required to do this without using the Array.prototype.flat() method.

Let’s write the code for this function −

Example

const arr = [
   5,
   7,
   [ 4, [2], 8, [1,3], 2 ],
   [ 9, [] ],
   1,
   8
];
const findNestedSum = (arr) => {
   let sum = 0;
   for(let len = 0; len < arr.length; len++){
      sum += Array.isArray(arr[len]) ? findNestedSum(arr[len]) :
      arr[len];
   };
   return sum;
};
console.log(findNestedSum(arr));

Output

The output in the console will be −

50

Updated on: 24-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements