Methods to Create Cumulative Sum Array
It can be done with the following methods:
Table of Content
- Method 1: Using JavaScript Loops
- Method 2: Using JavaScript array.map() Method
- Method 3: Using JavaScript array.forEach() Method
- Method 4: Using JavaScript array.reduce() Method
- Method 5: Using a Generator Function:
How to Create an Array of Cumulative Sum in JavaScript ?
This article will demonstrate how to create an array containing a cumulative sum at each index from an array of integers in JavaScript.
The Cumulative Sum is defined as the partial sum total for the given sequence and all its previous values at a certain index. It is also known as the running sum as it keeps on adding the sum of all previous values. For instance, consider the below array:
Arr = [ 2, 7, 9, 4, 3 ]
The Cumulative sum at every index will be:
0 : 2
1 : 2 + 7 = 9
2 : 2 + 7 + 9 = 18
3 : 2 + 7 + 9 + 4 = 22
4 : 2 + 7 + 9 + 4 + 3 = 25
Hence, the resulting array will be:
Cumulative Sum = [ 2, 9, 18, 22, 25 ]