How to use the map() method In Javascript
In this approach, we are using the inbuilt map() method which actually goes through every element of the array and stores the running sum, and also it returns the new array which consists of the cumulative sum at each index position.
Syntax:
map((element) => { /* … */ })
Example: In this example, we are using the map() method in JavaScript.
//Using map() method
let inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let cummulativeSum = 0;
let cumulativeSumArray = inputArray.map((element) => {
cummulativeSum += element;
return cummulativeSum;
});
let outputSum =
cumulativeSumArray[cumulativeSumArray.length - 1];
console.log("Cumulative Sum Array is:", cumulativeSumArray);
console.log("Total Cumulative Sum:", outputSum);
Output
Cumulative Sum Array is: [ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66 ] Total Cumulative Sum: 66
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.