How to use the map() method In Javascript

In this approach, we are using the inbuilt map() method which actually goes through every element of the array and stores the running sum, and also it returns the new array which consists of the cumulative sum at each index position.

Syntax:

map((element) => { /* … */ })

Example: In this example, we are using the map() method in JavaScript.

Javascript
//Using map() method
let inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let cummulativeSum = 0;

let cumulativeSumArray = inputArray.map((element) => {
    cummulativeSum += element;
    return cummulativeSum;
});

let outputSum =
    cumulativeSumArray[cumulativeSumArray.length - 1];

console.log("Cumulative Sum Array is:", cumulativeSumArray);
console.log("Total Cumulative Sum:", outputSum);

Output
Cumulative Sum Array is: [
   1,  3,  6, 10, 15,
  21, 28, 36, 45, 55,
  66
]
Total Cumulative Sum: 66


How to Calculate the Cumulative Sum of Elements in an Array using JavaScript?

In this article, we are going to learn to calculate the cumulative sum of elements in an array using JavaScript. The cumulative sum of elements in an array is a new array where each element represents the sum of all preceding elements, including itself, in the original array.

There are several methods that can be used to calculate the cumulative sum of elements in an array using JavaScript, which is listed below:

Table of Content

  • Using the forEach loop approach
  • Using the map() method in JavaScript
  • Using recursive function
  • Using the reduce Method

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Using the forEach loop approach

In this specified approach, we will be using the forEach loop to go through the individual element of the input array, and the current element is added to the running sum variable, and this calculated sum is actually saved in the new array. This iteration continues till the last element is been calculated....

Using the map() method in JavaScript

In this approach, we are using the inbuilt map() method which actually goes through every element of the array and stores the running sum, and also it returns the new array which consists of the cumulative sum at each index position....

Using recursive function

In this approach, we are using the recursion function to find the cumulative sum of array elements. The recursive function will go through the elements of the input given array, perform the add to the current element to the sum variable, and then store pr save each cumulative sum in the new array variable....

Using the reduce Method

The `reduce` method cumulatively processes array elements. Here, it accumulates the sum (`sum += num`) for each element and maps it to a new array. This provides a concise way to generate the cumulative sum by leveraging array transformation and accumulation in a single step....