.reduce()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Boiling a List Down to One Value
Imagine you want to calculate the total HP of your entire Codémon team. Instead of getting back another array, you want to combine all the items in the list into a single value (like a sum or a total score).
With `.forEach()`, you would create a variable outside the loop and add to it at each step:
const teamHp = [45, 30, 25];
let totalHp = 0;
teamHp.forEach((hp) => {
totalHp += hp;
});
console.log(totalHp);The `.reduce()` method does this exact job directly, without needing an external `let` variable. It carries a running result from one element to the next and returns the final value at the end:
const teamHp = [45, 30, 25];
const totalHp = teamHp.reduce((sum, hp) => sum + hp, 0);
console.log(totalHp);Exercise 2 — Anatomy of reduce
Let's break down how `.reduce()` works. It takes two arguments: a callback function and a starting value:
array.reduce((accumulator, element) => nextAccumulator, startingValue);1. `startingValue` (at the end, after the comma) sets the initial value of the accumulator (for example, `0` when adding numbers). 2. `accumulator` holds the running result carried from the previous step. 3. `element` is the current array item being visited. 4. Whatever your function returns becomes the new `accumulator` for the next element in the list.
Run this code to watch `sum` grow as it visits each Codémon's HP:
const teamHp = [45, 30, 25];
const totalHp = teamHp.reduce((sum, hp) => {
console.log("sum is " + sum + ", adding " + hp);
return sum + hp;
}, 0);
console.log("Final total: " + totalHp);Exercise 3 — Quiz: The Total
What does this code print?
const nums = [1, 2, 3, 4];
console.log(nums.reduce((a, b) => a + b, 0));10401234Hint : Carry the running value from one element to the next.
Exercise 4 — Sum the Levels
Add up every level, starting from 0.
Hint : The method that carries a value, the operation for a sum, and the neutral value to start from.
Exercise 5 — Don't Forget the Starting Value
The starting value in `.reduce()` is actually optional. If you leave it out on a normal array, JavaScript automatically uses the first element as the starting accumulator and begins looping from the second element:
const teamHp = [45, 30, 25];
// Starts with sum = 45, then adds 30 and 25
const totalHp = teamHp.reduce((sum, hp) => sum + hp);
console.log(totalHp);However, if the array happens to be empty, leaving out the starting value crashes your program because there is no first element to start with:
const emptyTeam = [];
console.log(emptyTeam.reduce((sum, hp) => sum + hp));For this reason, I advise you to always pass a starting value (like `0` for a sum) so your `.reduce()` never crashes, even on an empty list.
Exercise 6 — Quiz: Starting at 100
What does this code print?
const damage = [10, 20];
console.log(damage.reduce((hp, d) => hp - d, 100));7030100-30Hint : The starting value is the first accumulator, then each element is applied to it.
Exercise 7 — reduce on Objects
The elements can be objects, so the callback reads a property from each one. This is how you total a real list:
const team = [
{ name: "Aquachu", level: 12 },
{ name: "Pyrochu", level: 8 },
{ name: "Zap", level: 4 }
];
const total = team.reduce((sum, cdm) => sum + cdm.level, 0);
console.log("Total: " + total);
console.log("Average: " + total / team.length);Exercise 8 — Total HP
Add up the HP of the whole team.
Hint : Read the right property, and start a sum from its neutral value.
Exercise 9 — Not Only Numbers
The accumulator can be anything. With a string as the starting value, `reduce` builds text:
const team = ["Aquachu", "Zap", "Metachu"];
const line = team.reduce((text, name) => text + name + " ", "");
console.log(line);And with a number as the accumulator, you can keep the best value seen so far instead of a total:
const levels = [12, 4, 15, 8];
const best = levels.reduce((max, level) => {
if (level > max) {
return level;
}
return max;
}, 0);
console.log("Highest: " + best);Exercise 10 — Quiz: Which Method?
You want the total price of a list of items. Which method fits?
items.reduce(...)items.map(...)items.filter(...)items.some(...)Hint : One method turns a whole list into a single value.
Exercise 11 — reduce Cheat Sheet
Match each element with its role.
Exercise 12 — Shop Receipt
Produce the receipt for a shopping trip, using `reduce` for every number you need.
Step 1: print one line per item, in the format `"name x Q: X gold"`, where X is the price times the quantity. Step 2: with `reduce`, compute `total`, the sum of every price times its quantity, and print `"Total: X gold"`. Step 3: with `reduce`, compute `count`, the total number of units bought, and print `"Items: N"`. Step 4: with `reduce`, find the price of the most expensive item, and print `"Priciest: X gold"`.
Expected output:
Potion x 3: 90 gold
Elixir x 1: 120 gold
Map x 2: 80 gold
Total: 290 gold
Items: 6
Priciest: 120 goldconst cart = [
{ name: "Potion", price: 30, qty: 3 },
{ name: "Elixir", price: 120, qty: 1 },
{ name: "Map", price: 40, qty: 2 }
];
// Write your code here