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
How to sum all elements in a nested array? JavaScript
Let's say, we are supposed to write a function that takes in a nested array of Numbers and returns the sum of all the numbers. We are required to do this without using the Array.prototype.flat() method.
Let's write the code for this function ?
Using Recursive Approach
const arr = [
5,
7,
[ 4, [2], 8, [1,3], 2 ],
[ 9, [] ],
1,
8
];
const findNestedSum = (arr) => {
let sum = 0;
for(let len = 0; len < arr.length; len++){
sum += Array.isArray(arr[len]) ? findNestedSum(arr[len]) : arr[len];
}
return sum;
};
console.log(findNestedSum(arr));
50
How It Works
The function uses recursion to handle nested arrays:
- For each element, it checks if it's an array using
Array.isArray() - If it's an array, it recursively calls itself to sum that sub-array
- If it's a number, it adds it directly to the sum
- Empty arrays contribute 0 to the final sum
Alternative Using reduce()
const findNestedSumReduce = (arr) => {
return arr.reduce((sum, item) => {
return sum + (Array.isArray(item) ? findNestedSumReduce(item) : item);
}, 0);
};
const testArr = [1, [2, [3, 4], 5], 6, [7]];
console.log(findNestedSumReduce(testArr));
28
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| For Loop | Good | Slightly faster | More verbose |
| reduce() | Functional style | Slightly slower | More concise |
Conclusion
Both approaches effectively sum nested arrays using recursion. The for-loop version is slightly more performant, while the reduce() method offers cleaner functional programming style.
Advertisements
