Recursion - Sum Nested Array in JavaScript


We are required to write a JavaScript function that takes in a nested array of Numbers and returns the sum of all the numbers present in the array.

Let’s say the following is our nested array −

const arr = [2, 5, 7, [
   4, 5, 4, 7, [
       5, 7, 5
   ], 5
], 2];

Example

Following is the code −

const arr = [2, 5, 7, [
   4, 5, 4, 7, [
      5, 7, 5
   ], 5
], 2];
const calculateSum = (arr, query) => {
   let count = 0;
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         count += calculateSum(arr[i], query);
         continue;
      };
      count += arr[i];
   };
   return count;
};
console.log(calculateSum(arr));

Output

This will produce the following output in console −

58

Updated on: 30-Sep-2020

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements