In this lesson, you followed Marco’s teams through two chains of array methods, the final standings and the night’s perfect tens, and said what the data looked like after every step.
Key Points
- Each method in a chain is called on the array the step before it returned. Chains are usually written one step per line. To read a chain, say what each step hands on: how many items, and what each one looks like. That’s what the next step receives.
- In the standings chain, the first
.map()builds a new record for each team, and.reduce()inside it adds the team’s five rounds into one number. That step hands on five records, each with only anameand atotal. .toSorted()puts those records in order, highest total first. It still hands on five records of the same shape, and only the order changes. The last.map()turns each record into a line of text, so the chain ends with five strings.- Watch out: a chain that starts by calling
.sort()onteamsreorders Marco’s own array, because.sort()works in place..toSorted()always sorts a copy of the array, wherever it sits in a chain. The copy holds the same records. - Mapping each team to its
roundsgives five items, and each item is an array of five scores, so you have an array of arrays. Watch out: a.filter()for10on that array compares whole arrays with10, so it keeps none and gives[]. .flat()joins the inner arrays into one array of 25 numbers..flatMap()does both steps at once: it maps each team to its rounds, then flattens the result.- A long chain keeps its middle arrays out of sight. When Kwame doubted the Know-It-Owls’ 30, you named the first step’s array
totalsand logged it. The log showed their total was already 30 before the sort, because of their0in round three. Name a middle array you want to read, and leave a step you never need to see in the chain.
Final Code
Here’s standings.js, with the final standings as one chain: