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 ]

Similar Reads

Methods to Create Cumulative Sum Array

It can be done with the following methods:...

Method 1: Using JavaScript Loops

Looping in JavaScript is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true....

Method 2: Using JavaScript array.map() Method

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....

Method 3: Using JavaScript array.forEach() Method

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....

Method 4: Using JavaScript array.reduce() Method

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....

Method 5: Using a Generator Function:

A generator function can create an array of cumulative sums by iterating through the input array and yielding the cumulative sum at each step. By using the spread operator (…) with the generator function, you can generate the cumulative sum array efficiently....