Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Totaling With reduce()

Totaling With reduce()

The line that prints the average finish time has to work at the start gun, when the results page goes up and nobody has finished. The Python script adds the finish times with sum() and divides by max(len(seconds), 1), and prints Average finish: 95.6 min for the six finishers and Average finish: 0.0 min at the start gun, where nobody has a finish yet.

  • JavaScript has no sum() built-in. Arrays have a reduce() method, which folds the whole array into one value with a function you pass it, as with Python’s functools.reduce(). Math.max() keeps the guard, and .toFixed(1) rounds as :.1f does.
  • Ported as seconds.reduce((a, b) => a + b), the average matches for the race export. At the start gun, seconds is empty, and the port prints no average: it stops with TypeError: Reduce of empty array with no initial value.
  • Without an initial value, reduce() takes the array’s first item as the total and calls the function from the second item on. An empty array has no first item, so there’s no total to start from, and reduce() throws.
  • Python’s sum() has its start built in, a start parameter that defaults to 0, so the sum of an empty list is 0. Python’s functools.reduce() works like JavaScript’s reduce(): given an empty list and no initial value, it raises TypeError: reduce() of empty iterable with no initial value.
  • Pass the starting value as the second argument, and name the parameters for what they hold: seconds.reduce((total, s) => total + s, 0). The total starts at 0, and each call adds one finish time and returns the new total, which goes into the next call: 6157, 11605, 17385, 22649, 28352 and 34427 seconds. On an empty array, reduce() never calls the function and returns 0.
  • To count, as sum(1 for r in runners if r["finish"] == "DNF") does, keep the matches with filter() and read .length, as len() of a list comprehension would: one runner didn’t finish, and at the start gun, nobody.
  • A reduce() is a loop with a running total. When its function would take more than one line to follow, write that loop with for...of, a let total that starts at 0, and +=.
  • A newer built-in, Math.sumPrecise(), adds floats at least as carefully as Python’s sum(), but it isn’t in Node 26.

Here’s the average and the count, with the records trimmed to the two fields this code reads:

Language: JavaScript
const toSeconds = (time) => {
  const [h, m, s] = time.split(":").map(Number);
  return h * 3600 + m * 60 + s;
};

const runners = [
  { name: "Ana Ruiz", finish: "1:42:37" },
  { name: "Tom Okafor", finish: "1:30:48" },
  { name: "Mei Chen", finish: "1:36:20" },
  { name: "Lars Berg", finish: "DNF" },
  { name: "Priya Nair", finish: "1:27:44" },
  { name: "Sam Kowalski", finish: "1:35:03" },
  { name: "Jo Lindqvist", finish: "1:41:15" },
];
const finishers = runners.filter((r) => r.finish !== "DNF");

const seconds = finishers.map((r) => toSeconds(r.finish));
const sum = seconds.reduce((total, s) => total + s, 0);
const average = sum / Math.max(seconds.length, 1);
console.log(`Average finish: ${(average / 60).toFixed(1)} min`);

const dnf = runners.filter((r) => r.finish === "DNF").length;
console.log("Did not finish:", dnf);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 The live results page goes up at the start gun, so the line that prints the average finish time has to work before anyone has finished. Python turns each finish time into seconds, and sum() adds them up.

00:13 Dividing by the larger of the count and 1 keeps the average safe. For the six finishers, Python prints 95.6 minutes. At the start gun, nobody has a finish yet.

00:27 seconds is empty, sum() gives 0, and the line reads 0.0 minutes. JavaScript has no sum() built-in, so this line needs a different tool.

00:41 In the JavaScript port, the list comprehension becomes a map() over the finishers. Arrays have a reduce() method, which folds the whole array into one value.

00:51 You pass it a function that takes two values and returns one, as with Python’s functools.reduce(), and adding them gives the sum. Math.max() keeps the guard, and .toFixed() rounds to one decimal, as the format spec does.

01:06 Run it on the race export. It prints 95.6 minutes and matches Python. Now the start gun, with seconds empty, as it was for Python. What does the JavaScript print?

01:19 Your turn: pause the video and predict.

01:28 It prints no average at all.

01:32 JavaScript stops with a type error: reduce of empty array with no initial value.

01:39 The message names what’s missing: an initial value. Without one, reduce() takes the array’s first item as the total. It calls your function from the second item on: Ana’s time plus Tom’s, then that total plus Mei’s, and so on to Jo’s: five calls for six times.

02:00 An empty array has no first item, so there’s no total to start from, and reduce() throws. Python’s sum() has its start built in: a start parameter that defaults to 0.

02:13 That’s why the sum of an empty list is 0. Python’s functools.reduce() works like JavaScript’s. Given an empty list and no initial value, it raises a type error too.

02:27 The fix is a second argument: the value the total starts at, 0. Name the parameters for what they hold, the running total and the next time. Now reduce() starts the total at 0.

02:42 It calls your function with 0 and Ana’s time, and the function returns the new total. That total goes into the next call, with Tom’s time. One call per finisher, and after Jo’s, the total holds all six times.

02:58 On an empty array, reduce() never calls the function and returns the start value. Run both exports again. The race still gives 95.6, and the start gun now prints 0.0 minutes, as Python does.

03:15 The script’s last line counts the runners who didn’t finish. Python adds up a 1 for each match. In JavaScript, keep the matches with filter() and read the array’s length, as len() of a list comprehension would.

03:29 Run it: one runner, Lars Berg, didn’t finish, the same as in Python, and at the start gun, nobody. A reduce() is a loop with a running total.

03:42 When its function would take more than one line to follow, write that loop instead: a let total that starts at 0, and plus-equals for each time.

03:52 A newer built-in, Math.sumPrecise(), adds floats at least as carefully as Python’s sum(), but it isn’t in Node 26.

04:02 JavaScript has no sum() built-in, so a total is a reduce() with a starting value. Always pass that value, so an empty array totals to 0 instead of throwing.

04:13 Count matches by filtering, then reading the length. When a reduce() gets hard to follow, a plain loop with a running total is the clearer JavaScript.

04:25 Next up is Finding the Fastest With Math.min(), a video. There, you’ll find the fastest finish time, then the fastest runner, with reduce() keeping the better runner each time.

Become a Member to join the conversation.