How to use array.forEach() Method In Javascript
The array.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array.
Syntax:
array.forEach( callback( element, index, arr ), thisValue )
Example: In this example, we will create Cumulative Sum Array using JavaScript array.map() method.
// Create an array
const arr = [1, 3, 5, 7, 9, 11];
// Create variable to store sum
let sum = 0;
// Create resulting array
let cumulativeSum = []
// Using forEach method to iterate
// and perform required operation
arr.forEach((e)=>{
sum = sum + e;
cumulativeSum.push(sum);
})
// Display the output
console.log(cumulativeSum);
Output
[ 1, 4, 9, 16, 25, 36 ]
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 ]