
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Recursion - Sum Nested Array in JavaScript
We are required to write a JavaScript function that takes in a nested array of Numbers and returns the sum of all the numbers present in the array.
Let’s say the following is our nested array −
const arr = [2, 5, 7, [ 4, 5, 4, 7, [ 5, 7, 5 ], 5 ], 2];
Example
Following is the code −
const arr = [2, 5, 7, [ 4, 5, 4, 7, [ 5, 7, 5 ], 5 ], 2]; const calculateSum = (arr, query) => { let count = 0; for(let i = 0; i < arr.length; i++){ if(Array.isArray(arr[i])){ count += calculateSum(arr[i], query); continue; }; count += arr[i]; }; return count; }; console.log(calculateSum(arr));
Output
This will produce the following output in console −
58
- Related Questions & Answers
- Weight sum of a nested array in JavaScript
- Function to flatten array of multiple nested arrays without recursion in JavaScript
- Sum of nested object values in Array using JavaScript
- How to sum all elements in a nested array? JavaScript
- JavaScript recursive loop to sum all integers from nested array?
- Simplifying nested array JavaScript
- Grouping nested array in JavaScript
- Prefix sums (Creating an array with increasing sum) with Recursion in JavaScript
- Array sum: Comparing recursion vs for loop vs ES6 methods in JavaScript
- Join in nested array in JavaScript
- Python Program to Find the Total Sum of a Nested List Using Recursion
- Convert nested array to string - JavaScript
- Array flattening using loops and recursion in JavaScript
- Transform nested array into normal array with JavaScript?
- Group objects inside the nested array JavaScript
Advertisements