Sum All Integers from Nested Array using Recursive Loop in JavaScript



You need to call the same function again and again to sum all integers from nested array. Following is the code −

Example

function sumOfTotalArray(numberArray){
   var total= 0;
   for (var index = 0; index < numberArray.length; index++) {
      if (numberArray[index] instanceof Array){
         total=total+sumOfTotalArray(arr[index]);
      }
      if (numberArray[index] === Math.round(numberArray[index])){
         total=total+numberArray[index];
      }
   }
   return total;
}
var number = new Array(6);
number=[10,20,30,40,50,60];
console.log("The sum is="+sumOfTotalArray(number));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo53.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo53.js
The sum is=210
Updated on: 2020-09-03T06:49:42+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements