

- 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
Modified version of summing an array with recursion in JavaScript
Let’s say, we are required to write a recursive function that sums all the elements of an array of Numbers but with a twist and the twist is that the recursive function we write cannot initialize any extra variable (memory).
Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all has to be using what we already have.
Here’s the solution −
We already have an array and can use its first element (i.e., the element at zeroth index to hold the recursive sum).
The approach is that we repeatedly pop one element from the array and add it to the first element of the array until we are left with only one element.
When we are left with only one element, it will be the cumulative sum of the array and we return that. The code for this approach will be −
Example
const recursiveSum = arr => { if(arr.length > 1){ arr[0] += arr.pop(); return recursiveSum(arr); }; return arr[0]; }; console.log(recursiveSum([1,2,3,4])); console.log(recursiveSum([1,2,3,4,3,6,3,32,7,9,5])); console.log(recursiveSum([]));
Output
The output in the console will be −
10 75 undefined
- Related Questions & Answers
- Summing all the unique values of an array - JavaScript
- Summing array of string numbers using JavaScript
- Finding product of an array using recursion in JavaScript
- Combine unique items of an array of arrays while summing values - JavaScript
- Comparing forEach() and reduce() for summing an array of numbers in JavaScript.
- Prefix sums (Creating an array with increasing sum) with Recursion in JavaScript
- Summing up unique array values in JavaScript
- Find the middle element of an array using recursion JavaScript
- JavaScript - summing numbers from strings nested in array
- Recursion - Sum Nested Array in JavaScript
- Summing up to amount with fewest coins in JavaScript
- Using recursion to remove consecutive duplicate entries from an array - JavaScript
- How to insert an element into all positions in an array using recursion - JavaScript?
- Using recursion to remove consecutive duplicate entries from an array in JavaScript
- JavaScript - filtering array with an array