 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Example
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));  Output
The output in the console will be −
50
Advertisements
 