How to use the forEach loop approach In Javascript
In this specified approach, we will be using the forEach loop to go through the individual element of the input array, and the current element is added to the running sum variable, and this calculated sum is actually saved in the new array. This iteration continues till the last element is been calculated.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Example: In this example, we are using the forEach loop approach in JavaScript
// Using forEach loop
let inputArray = [1, 2, 3, 4, 5, 6, 7];
let cummulativeSum = 0;
let outputCummulativeSumArray = [];
inputArray.forEach((element) => {
cummulativeSum += element;
outputCummulativeSumArray.push(cummulativeSum);
});
const outputSum =
outputCummulativeSumArray[outputCummulativeSumArray.length - 1];
console.log("Cumulative Sum Array is:", outputCummulativeSumArray);
console.log("Total Cumulative Sum:", outputSum);
Output
Cumulative Sum Array is: [ 1, 3, 6, 10, 15, 21, 28 ] Total Cumulative Sum: 28
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.