Calculate a running total (cumulative sum) in JavaScript
Intermediate · 4 min read
A running total, also called a cumulative sum, turns each item into "this one plus everything before it". Daily sales [1, 2, 3, 4] become [1, 3, 6, 10]: the total so far at the end of each day. Bank statements show a running balance, progress bars show a running count, and charts of "total sign-ups over time" are running totals.
In this tutorial you will build a running total with map, then a running maximum, then compare it with a reduce version and see why that version gets slow. Finally you will undo a running total to get the original list back. You should know arrays, map and arrow functions.
An assignment gives back a value
In JavaScript, total += n doesn't only change total. The whole expression also has a value: the new total.
let total = 10;
console.log((total += 5)); // 15
console.log(total); // 15
That means an arrow function can update a variable and return the new value in one go: (n) => (total += n). The extra brackets make it clear that you meant to return the result of the assignment.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
36 Running totals
fairTurn [1, 2, 3, 4] into [1, 3, 6, 10]: each element plus everything before it. Then do a running maximum, and recover the original list from the totals.
Stuck? Three hints, smallest first
- 1. A
mapwith one variable outside it is the cheapest version:total += nas the returned value. - 2.
total += nis an expression, so an arrow can return it directly. - 3. The inverse is the differences between neighbours, with the first element left as it is.
Step 1: a running sum with map
Keep the total in a variable outside the map. Each call adds the current item and returns the new total, and map collects those totals into a new list.
function cumulative(xs) {
let total = 0;
return xs.map((n) => (total += n));
}
const sales = [1, 2, 3, 4];
console.log(cumulative(sales)); // [ 1, 3, 6, 10 ]
console.log(cumulative(sales).at(-1)); // 10
console.log(cumulative([])); // []
console.log(sales); // [ 1, 2, 3, 4 ]
The last total is the sum of everything, and .at(-1) reads the last item. An empty list gives an empty list. The output is always the same length as the input, and the input is not changed.
total lives inside cumulative, so each call starts fresh at 0. If you put let total = 0 outside the function, a second call would carry on from where the first one stopped.
Step 2: negative numbers
function cumulative(xs) {
let total = 0;
return xs.map((n) => (total += n));
}
console.log(cumulative([5, -2, 1])); // [ 5, 3, 4 ]
A running total can go down. A bank balance with a withdrawal looks just like this.
Step 3: a running maximum
The same shape works for other "so far" values. A running maximum keeps the largest value seen so far.
const runningMax = (xs) => {
let best = -Infinity;
return xs.map((n) => (best = Math.max(best, n)));
};
console.log(runningMax([1, 3, 2, 5, 4])); // [ 1, 3, 3, 5, 5 ]
best starts at -Infinity, a value smaller than every number, so the first item always replaces it. A running maximum can never go down: after 3, the 2 doesn't change it. Think of "personal best so far" in a game.
Step 4: the reduce version
You will also see running totals written with reduce, building the list as the accumulator.
const cumulativeReduce = (xs) => xs.reduce((acc, n) => [...acc, (acc.at(-1) ?? 0) + n], []);
console.log(cumulativeReduce([1, 2, 3, 4])); // [ 1, 3, 6, 10 ]
Each step reads the last total (acc.at(-1), or 0 for the very first step), adds n, and returns a new list with the new total on the end.
The answer is the same, but look at [...acc, ...]. That copies the whole list so far, on every single step. For 4 items it copies 0, then 1, then 2, then 3 items. For 10,000 items it copies about 50 million. The work grows with the square of the length, which programmers call quadratic. The map version does one pass and builds one list. Past a few hundred items, prefer map.
Step 5: undo a running total
To get the original list back, take the difference between each total and the one before it. The first total has nothing before it, so it stays as it is.
function cumulative(xs) {
let total = 0;
return xs.map((n) => (total += n));
}
const differences = (totals) => totals.map((t, i) => (i === 0 ? t : t - totals[i - 1]));
console.log(differences([1, 3, 6, 10])); // [ 1, 2, 3, 4 ]
console.log(differences(cumulative([5, -2, 1]))); // [ 5, -2, 1 ]
map passes the index as its second argument, so totals[i - 1] is the previous total. Running a list through cumulative and then differences always gets you back where you started.
Is changing total allowed?
Some people say a map callback should never change a variable outside itself. That is a good rule in general. Here it is fine: total is created inside cumulative and nothing outside can see it. From the outside, cumulative takes a list and returns a new one, with no side effects. That is the property that matters.
The full solution
The panel defines cumulative, runningMax, cumulativeReduce and differences, then runs them on the sales list. Press Run and check that the differences line matches the input.
function cumulative(xs) {
let total = 0;
return xs.map((n) => (total += n)); // += evaluates to the new total
}
const runningMax = (xs) => {
let best = -Infinity;
return xs.map((n) => (best = Math.max(best, n)));
};
// The same thing with reduce, which copies the accumulator on every step.
const cumulativeReduce = (xs) => xs.reduce((acc, n) => [...acc, (acc.at(-1) ?? 0) + n], []);
// The inverse: differences.
const differences = (totals) => totals.map((t, i) => (i === 0 ? t : t - totals[i - 1]));
const sales = [1, 2, 3, 4];
console.log('input :', sales);
console.log('running sum :', cumulative(sales));
console.log('reduce version:', cumulativeReduce(sales));
console.log('running max :', runningMax([1, 3, 2, 5, 4]));
console.log('differences :', differences(cumulative(sales)), '<- back to the input');
console.log('the last total is the sum:', cumulative(sales).at(-1));
console.log('empty :', cumulative([]));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a running sum', cumulative(sales), [1, 3, 6, 10]);
test('the last value is the total', cumulative(sales).at(-1), 10);
test('the reduce version agrees', cumulativeReduce(sales), cumulative(sales));
test('an empty list gives an empty list', cumulative([]), []);
test('a running maximum never goes down', runningMax([1, 3, 2, 5, 4]), [1, 3, 3, 5, 5]);
test('differences undo a running sum', differences(cumulative(sales)), sales);
test('negative values make a running sum fall', cumulative([5, -2, 1]), [5, 3, 4]);
test('the output is always the same length as the input', cumulative([1, 2, 3]).length, 3);
test('and the input is untouched', sales, [1, 2, 3, 4]);
Both versions are correct and they do not cost the same. The map with a variable beside it does one pass and allocates one array. The reduce version builds a fresh array on every step, so it copies 1 + 2 + 3 + ... + n elements — quadratic work for a linear problem. It reads more "functionally" and is the wrong choice past a few hundred elements.
A closure over a mutable total inside map is sometimes called impure and frowned on. It is fine here: the variable never escapes the function, so the function as a whole is still pure, which is the property that actually matters.
Common mistakes
- Declaring
totaloutside the function. The second call continues from the first call's total. - Forgetting the brackets around
total += n. Without them, a reader may think you meant===. Write(n) => (total += n)to make the return clear. - Using the
reduceversion on long lists. It copies the list at every step. Usemapwith a variable.
Try it yourself
- Write
runningMinthat keeps the smallest value so far. - Turn
[200, -50, 120, -300]into running balances starting from an opening balance of1000. - Write
runningAverage(xs)that gives the average of everything so far at each position.