Emmanuel Akinfulubi

JavaScriptMath

Cumulative sums and running average in JavaScript

Intermediate · 5 min read

A bank statement shows a balance after every transaction. A fitness app shows your steps so far today. A sales dashboard shows the year-to-date total. Each of these is a cumulative sum, also called a running total: every entry is the sum of everything up to that point.

In this tutorial you will turn a list of sales into running totals, get the original list back from them, see what happens when you keep adding 0.1, and keep a running average without storing a total at all. You need to know arrays, map and arrow functions.

Running totals by hand

Take the daily sales 5, 10, 15 and 20.

  • After day 1 the total is 5.
  • After day 2 it is 5 + 10 = 15.
  • After day 3 it is 15 + 15 = 30.
  • After day 4 it is 30 + 20 = 50.

So the running totals are 5, 15, 30 and 50. Each one is the previous total plus today's value. The last one, 50, is the grand total.

A variable that map can see

A function created inside another function can read and change that outer function's variables. This is called a closure. It lets a map callback keep a total between calls:

JavaScript

let total = 0;
const totals = [1, 2, 3].map((x) => (total += x));
console.log(totals); // [ 1, 3, 6 ]

total += x adds x to total and also gives back the new value, so map puts that new value into the result array.

Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.

64 Cumulative sums, and a running mean

fair

Turn a list into its running totals, and get the original back by differencing. Then run ten lots of 0.1 through it, and keep a running mean without keeping a running total.

Stuck? Three hints, smallest first
  1. 1. A closure over a total plus map gives the scan: xs.map((x) => (total += x)).
  2. 2. The last cumulative value is the grand total, and differencing undoes the whole thing.
  3. 3. Welford: m += (x - m) / (i + 1) updates a mean without ever holding a sum.

Step 1: cumulative sums

Wrap that idea in a function, so each call starts with its own fresh total of 0:

Step 1

function cumulative(xs) {
  let total = 0;
  return xs.map((x) => (total += x));
}
const sales = [5, 10, 15, 20];
const cum = cumulative(sales);
console.log(cum);                 // [ 5, 15, 30, 50 ]
console.log(cum[cum.length - 1]); // 50
console.log(cumulative([]));      // []

The output matches the totals worked out by hand. The last entry is the grand total, and an empty list gives an empty list.

One thing to know: this callback is not "pure", because it changes total each time it runs. That is fine here, because map always visits items in order. Don't reuse the pattern anywhere that might run the callbacks in a different order.

Step 2: getting the original list back

To undo running totals, subtract each total from the one before it. This is called differencing. The first entry has nothing before it, so it stays as it is.

Step 2

const differences = (cs) => cs.map((c, i) => (i === 0 ? c : c - cs[i - 1]));
console.log(differences(cum)); // [ 5, 10, 15, 20 ]

map passes the index i as a second argument, so cs[i - 1] is the previous total. We got the sales back exactly. That makes differencing a cheap check for any code that stores running totals: difference them, and compare with the original data.

Step 3: ten lots of 0.1

Now add 0.1 ten times. You would expect the last total to be 1.

Step 3

const tenths = Array(10).fill(0.1);
const run = cumulative(tenths);
console.log(run[2]); // 0.30000000000000004
console.log(run[9]); // 0.9999999999999999

Array(10).fill(0.1) makes a list of ten 0.1s. The third total is already slightly off, and the tenth comes out just under 1.

The reason: 0.1 can't be stored exactly in binary, so each addition rounds a little. In a running total those small errors don't cancel out. They build up, entry by entry. A balance kept this way slowly drifts away from the figure a customer would work out by hand.

Step 4: the same payments in whole units

The usual fix for money is to count in the smallest unit as whole numbers. In Nigeria that is kobo (100 kobo make 1 naira), so 0.1 naira is 10 kobo:

Step 4

const koboTenths = Array(10).fill(10);      // 10 kobo, ten times
console.log(cumulative(koboTenths)[9]); // 100

Whole numbers add exactly, so ten payments of 10 kobo come to exactly 100 kobo, which is 1 naira. Convert to naira only when you display the amount.

Step 5: a running average without a total

A running average (running mean) is the average of everything so far. The obvious way is to keep a running total and divide it by the count. There is another way that never stores a total: nudge the current mean toward each new value.

Output

new mean = old mean + (new value - old mean) / count

If the new value is above the mean, the mean goes up a little. The bigger the count, the smaller the nudge, because one new value matters less when you have already seen many. This update is known as Welford's method.

Step 5

function runningMean(xs) {
  let m = 0;
  return xs.map((x, i) => (m += (x - m) / (i + 1)));
}
const marks = [72, 88, 61, 95, 79];
console.log(runningMean(marks)); // [ 72, 80, 73.66666666666667, 79, 79 ]

i + 1 is the count so far, because indexes start at 0. The first entry is just the first mark, 72. After two marks, the mean is 80, and the last entry, 79, is the plain mean of all five:

JavaScript

console.log(marks.reduce((a, b) => a + b, 0) / marks.length); // 79

Because it holds no total, this version can't build up a huge sum that loses its low digits, which is a problem with very long lists of large numbers.

The full solution

The answer panel has cumulative, differences and runningMean, and prints the running totals of the sales, the differenced list, the grand total, the ten tenths, the same payments in kobo, and the running mean of the marks. Press Run to see the output.

The answer

function cumulative(xs) {
  let total = 0;
  return xs.map((x) => (total += x));
}

const differences = (cs) => cs.map((c, i) => (i === 0 ? c : c - cs[i - 1]));

// A mean that never stores a total, so it cannot overflow one.
function runningMean(xs) {
  let m = 0;
  return xs.map((x, i) => (m += (x - m) / (i + 1)));
}

const sales = [5, 10, 15, 20];
const tenths = Array(10).fill(0.1);
const koboTenths = Array(10).fill(10);      // 10 kobo, ten times
const marks = [72, 88, 61, 95, 79];

const cum = cumulative(sales);

console.log('cumulative   :', cum);
console.log('differenced  :', differences(cum));
console.log('grand total  :', cum[cum.length - 1]);
console.log('ten tenths   :', cumulative(tenths));
console.log('in kobo      :', cumulative(koboTenths));
console.log('running mean :', runningMean(marks));

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.

9 checks

test('four sales figures become their running totals', cum, [5, 15, 30, 50]);
test('the last entry is the grand total', cum[cum.length - 1], 50);
test('differencing gives the original list back', differences(cum), sales);
test('an empty list scans to an empty list', cumulative([]), []);
test('ten lots of 0.1 cumulate to 0.9999999999999999, not 1', cumulative(tenths)[9], 0.9999999999999999);
test('and the drift shows up as early as the third entry', cumulative(tenths)[2], 0.30000000000000004);
test('the same ten payments in kobo land on 100 exactly', cumulative(koboTenths)[9], 100);
test('a running mean ends on the plain mean, holding no total at all', [runningMean(marks)[4], marks.reduce((a, b) => a + b, 0) / 5], [79, 79]);
test('and its first entry is just the first value', runningMean(marks)[0], 72);

A cumulative sum is a scan rather than a fold: it keeps every intermediate. Written with map and a closed-over total it is one line, and it reads clearly, but note that the callback is not pure — reordering or parallelising it would give nonsense. Differencing is the exact inverse for integers, which makes it a cheap self-check on any pipeline that stores running totals.

Ten additions of 0.1 reach 0.9999999999999999. Each one rounds, and the errors accumulate rather than cancel, so a running balance built this way drifts steadily away from the figure a customer would compute by hand. Integer kobo lands on 100 exactly. Welford's running mean is the other lesson: m += (x - m) / (i + 1) holds no sum, so it cannot overflow one and it does not lose the low bits of a large total — the same idea that fixes the variance in exercise 60.

Common mistakes

  • Declaring the total outside the function. A shared total keeps growing between calls, so the second list starts from the first list's grand total.
  • Expecting ten 0.1s to make exactly 1. They make 0.9999999999999999. For money, use whole units such as kobo.
  • Dividing by i instead of i + 1 in the running mean. On the first item that is a division by 0, and the mean becomes Infinity.

Try it yourself

  1. Use cumulative on a week of step counts, [4200, 8100, 6500, 9900, 3000, 12000, 7600], and find the day you passed 30,000 steps.
  2. Write runningMax(xs) that returns the largest value seen so far at each position.
  3. Run differences(cumulative(tenths)) and see whether you get ten exact 0.1s back.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.