Converting array of Numbers to cumulative sum array in JavaScript

We have an array of numbers like this:

const arr = [1, 1, 5, 2, -4, 6, 10];

We are required to write a function that returns a new array, of the same size but with each element being the sum of all elements until that point (cumulative sum).

Therefore, the output should look like:

const output = [1, 2, 7, 9, 5, 11, 21];

Let's explore different approaches to create a cumulative sum array.

Using forEach() Method

We can iterate through the array and build the cumulative sum by adding each element to the previous cumulative value:

const arr = [1, 1, 5, 2, -4, 6, 10];

const partialSum = (arr) => {
    const output = [];
    arr.forEach((num, index) => {
        if(index === 0){
            output[index] = num;
        }else{
            output[index] = num + output[index - 1];
        }
    });
    return output;
};

console.log(partialSum(arr));
[ 1, 2, 7, 9, 5, 11, 21 ]

Using map() Method

A more functional approach using map() with a running sum variable:

const arr = [1, 1, 5, 2, -4, 6, 10];

const cumulativeSum = (arr) => {
    let sum = 0;
    return arr.map(num => sum += num);
};

console.log(cumulativeSum(arr));
[ 1, 2, 7, 9, 5, 11, 21 ]

Using reduce() Method

Using reduce() to build the cumulative array step by step:

const arr = [1, 1, 5, 2, -4, 6, 10];

const cumulativeSumReduce = (arr) => {
    return arr.reduce((acc, num, index) => {
        if (index === 0) {
            acc.push(num);
        } else {
            acc.push(num + acc[index - 1]);
        }
        return acc;
    }, []);
};

console.log(cumulativeSumReduce(arr));
[ 1, 2, 7, 9, 5, 11, 21 ]

Comparison

Method Readability Performance Functional Style
forEach() Good Fast No
map() Excellent Fast Yes
reduce() Good Moderate Yes

How It Works

Each approach follows the same logic: iterate through the array and maintain a running sum. The current element is added to the previous cumulative sum to get the new cumulative value. The first element remains unchanged as there's no previous sum to add to.

Conclusion

The map() method with a running sum variable provides the cleanest and most readable solution for creating cumulative sum arrays. All methods produce the same result, so choose based on your coding style preference.

Updated on: 2026-03-15T23:19:00+05:30

644 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements