Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript recursive loop to sum all integers from nested array?


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