How to use array.map() Method In Javascript
The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is used to iterate and perform iterations over an array.
Syntax:
map((element) => { /* … */ })
Example: In this example, we will see how to create an array having a cumulative sum using JavaScript array.map() map.
// Create a new array
const arr = [1, 3, 5, 7, 9, 11];
// Variable to store sum
let sum = 0;
// Creating final array
let cumulativeSum = []
// Using map to perform transformations
arr.map((e)=>{
sum = sum + e;
cumulativeSum.push(sum);
})
// Display 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 ]