- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- JavaScript recursive loop to sum all integers from nested array?
- Sum all similar elements in one array - JavaScript
- Recursion - Sum Nested Array in JavaScript
- How to find the sum of all elements of a given array in JavaScript?
- Weight sum of a nested array in JavaScript
- How to find the sum of all array elements in R?
- Sum of nested object values in Array using JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Consecutive elements sum array in JavaScript
- Reducing array elements to all odds in JavaScript
- How to filter an array from all elements of another array – JavaScript?
- Finding sum of all unique elements in JavaScript
- Absolute sum of array elements - JavaScript
- Sum all duplicate value in array - JavaScript
- How to sum elements at the same index in array of arrays into a single array? JavaScript

Advertisements