JavaScript recursive loop to sum all integers from nested array?

JavaScript recursive functions can process nested arrays by calling themselves repeatedly to handle arrays within arrays. This technique is essential for working with complex data structures of unknown depth.

Example: Basic Recursive Sum

function sumOfTotalArray(numberArray) {
    var total = 0;
    for (var index = 0; index 

The sum is=210

Example: Nested Arrays

Here's how the function handles deeply nested arrays:

function sumNestedArray(arr) {
    let total = 0;
    for (let i = 0; i 

Nested array sum: 28
Deep nested sum: 21

How It Works

The recursive function follows these steps:

  1. Loop through elements: Iterate through each item in the array
  2. Check type: Determine if the element is an array or number
  3. Recursive call: If it's an array, call the function again
  4. Base case: If it's a number, add it to the total
  5. Return result: Sum all values and return the total

Modern Approach with Array.flat()

For simpler cases, you can flatten the array first:

function sumFlattenedArray(arr) {
    return arr.flat(Infinity).reduce((sum, num) => sum + num, 0);
}

let nestedArray = [1, [2, 3], [4, [5, 6]], 7];
console.log("Flattened sum:", sumFlattenedArray(nestedArray));
Flattened sum: 28

Comparison

Method Performance Browser Support Flexibility
Recursive Function Good All browsers High - can handle mixed types
Array.flat() + reduce() Better ES2019+ Limited - numbers only

Conclusion

Recursive functions provide a clean solution for summing nested arrays of any depth. The recursive approach checks each element and calls itself for nested arrays, making it ideal for complex data structures.

Updated on: 2026-03-15T23:18:59+05:30

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements