Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
-
Loop through elements: Iterate through each item in the array
-
Check type: Determine if the element is an array or number
-
Recursive call: If it's an array, call the function again
-
Base case: If it's a number, add it to the total
-
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.
Advertisements
