How to use array.reduce() Method In Javascript
The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr), initialValue );
Example: This example will demonstrate how we can create an array having a cumulative sum using JavaScript array.reduce() method.
// Declare new array
const arr = [1, 3, 5, 7, 9, 11];
// Initialize cumulative array
let cumulativeSum = [];
// Callback function to execute in reduce method
function execute(sum,element){
sum = sum + element;
cumulativeSum.push(sum);
return sum
}
// Using array.reduce with the Callback function
arr.reduce(execute,0);
// 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 ]