How to make a list of partial sums using forEach JavaScript

In JavaScript, creating a list of partial sums (also known as cumulative sums) means generating a new array where each element represents the sum of all elements up to that position in the original array.

We have an array of numbers like this:

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

We need to create a function that returns a new array where each element is the sum of all previous elements including itself:

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

Using forEach Method

The forEach method iterates through each element and maintains a running total. Here's the implementation:

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
]

How It Works

The function iterates through the array using forEach:

  • For the first element (index 0), it directly assigns the value to the output array
  • For subsequent elements, it adds the current number to the previous partial sum
  • Each iteration builds upon the previous cumulative sum

Alternative Approach Using Running Sum

Here's a cleaner version that maintains a running sum variable:

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

const partialSumImproved = (arr) => {
    const output = [];
    let runningSum = 0;
    
    arr.forEach(num => {
        runningSum += num;
        output.push(runningSum);
    });
    
    return output;
};

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

Comparison with Other Methods

Method Readability Performance Mutates Original
forEach Good Fast No
map Better Fast No
reduce Complex Fast No

Conclusion

The forEach method provides a straightforward approach to calculate partial sums by maintaining a running total. This technique is useful for creating cumulative statistics and progressive calculations in data analysis.

Updated on: 2026-03-15T23:18:59+05:30

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements