- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Advertisements