How to use recursive function In Javascript
In this approach, we are using the recursion function to find the cumulative sum of array elements. The recursive function will go through the elements of the input given array, perform the add to the current element to the sum variable, and then store pr save each cumulative sum in the new array variable.
Syntax:
function functionName(/* parameters */) {
if (/* base case condition */) {
// return some value or perform an action
}
}
Example: In this example, we are using the recursive function in JavaScript.
//Using Recursion
let inputArray = [1, 2, 3, 4];
let totalCummaltiveArray = [];
let cummulativeSum = 0;
function calculateCumulativeSumUsingRecursion(index) {
if (index < inputArray.length) {
cummulativeSum += inputArray[index];
totalCummaltiveArray.push(cummulativeSum);
calculateCumulativeSumUsingRecursion(index + 1);
}
}
calculateCumulativeSumUsingRecursion(0);
let outputSum = totalCummaltiveArray[totalCummaltiveArray.length - 1];
console.log("Cumulative Sum Array is:", totalCummaltiveArray);
console.log("Total Cumulative Sum:", outputSum);
Output
Cumulative Sum Array is: [ 1, 3, 6, 10 ] Total Cumulative Sum: 10
How to Calculate the Cumulative Sum of Elements in an Array using JavaScript?
In this article, we are going to learn to calculate the cumulative sum of elements in an array using JavaScript. The cumulative sum of elements in an array is a new array where each element represents the sum of all preceding elements, including itself, in the original array.
There are several methods that can be used to calculate the cumulative sum of elements in an array using JavaScript, which is listed below:
Table of Content
- Using the forEach loop approach
- Using the map() method in JavaScript
- Using recursive function
- Using the reduce Method
We will explore all the above methods along with their basic implementation with the help of examples.