javascript · level 2 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
folds a whole array down into one value.
.reduce() walks through an array carrying one value along, like a snowball rolling downhill and growing. That carried value is the . Your function gets the accumulator and the next item, and hands back the new accumulator.
The second argument is the starting value. prices.reduce((sum, price) => sum + price, 0) starts at 0, then adds each price. When the array runs out, the final accumulator is the answer.
Always give a starting value. It keeps empty arrays safe and makes the code easier to read.
const prices = [3, 5, 2];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total);
const basket = [{ item: "milk", price: 1 }, { item: "bread", price: 2 }];
const bill = basket.reduce((sum, line) => sum + line.price, 0);
console.log(`Bill: £${bill}`); It is the running total from Level 1, folded into a single line.
guess first
Two reduces over the beach words. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const words = ["sun", "sea", "sand"];
const letters = words.reduce((count, word) => count + word.length, 0);
const joined = words.reduce((text, word) => text + word, "");
console.log(letters, joined);
your turn
Your turn. Total a week of steps.
Add two more days of steps to the array, then fill in the starting value for the total. Press run.
fix it
The total starts with something strange. Fix it!
- The total starts with [object Object]. What is
sumon the very first turn? - With no starting value,
reduceuses the first item, a whole object, as the first sum. - Add , 0 before the last closing bracket on line 2, so the sum starts at 0, then press run.
nailed it
you boiled an array down to one value. :D
reducecarries an accumulator through every item.- The function hands back the new accumulator each time.
- Always give a starting value as the second argument.
new words in your collection
- reduce
- accumulator
This lesson isn’t saved. A free account remembers every lesson you finish.