How to use the reduce Method In Javascript
The `reduce` method cumulatively processes array elements. Here, it accumulates the sum (`sum += num`) for each element and maps it to a new array. This provides a concise way to generate the cumulative sum by leveraging array transformation and accumulation in a single step.
Example: In this example The function cumulativeSum computes the cumulative sum of elements in an array, returning an array with each element representing the sum up to that index.
function cumulativeSum(arr) {
let sum = 0;
return arr.map(num => sum += num);
}
let array = [1, 2, 3, 4];
console.log(cumulativeSum(array));
Output
[ 1, 3, 6, 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.