11.1 map: A New Array from Every Element
Before you start, set up a new project folder named day11 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.
Since Day 5 you have written the same loop again and again: declare an empty result, go through an array with for...of, and push something for each element. Here it is once more, adding 20% tax to a list of prices:
const prices = [4, 10, 2.5];
const withTax: number[] = [];
for (const price of prices) {
withTax.push(price * 1.2);
}
console.log(withTax);[ 4.8, 12, 3 ]
Four lines of plumbing (lines 2 to 5) carry one line of real work: price * 1.2. Every array has methods that do this plumbing for you. Each one takes a callback, the idea from Day 10: a function you hand over, which the method calls once for each element. The method then does something with the callback’s answers. The first and most common of these methods is map.
items.map(callback) calls the callback once for each element of items, in order, and gives back a new array of the callback’s results, one for each element and in the same positions. The original array is not changed.
Worked example: Adding tax with map
const prices = [4, 10, 2.5];
const withTax = prices.map((price) => price * 1.2);
console.log(withTax);
console.log(prices);[ 4.8, 12, 3 ]
[ 4, 10, 2.5 ]Line 2 does everything the loop did. Read it from left to right: take prices, and for each one, call (price) => price * 1.2. The arrow function is Day 8’s shortest form, with one parameter and one expression that is returned.
| Call | price |
Callback returns | Position in the new array |
|---|---|---|---|
| 1 | 4 | 4.8 | 0 |
| 2 | 10 | 12 | 1 |
| 3 | 2.5 | 3 | 2 |
map collects the three results into [4.8, 12, 3] and gives that array back; withTax holds it. Line 4 shows that prices is exactly as it was. The new array always has the same length as the old one, because every element produces exactly one result.
Now vary what the callback returns. It does not have to be the same kind of value as the element. Here each number becomes a price label:
const prices = [4, 10, 2.5];
const labels = prices.map((price) => `$${price.toFixed(2)}`);
console.log(labels);
console.log(labels.length, typeof labels[0]);[ '$4.00', '$10.00', '$2.50' ]
3 string
prices is a number[], and labels is a string[]: hover over it in VS Code and you will see const labels: string[]. The checker worked that out from the callback, which returns a template literal. (Node shows strings inside an array with single quotes; that is only how it prints them.)
A callback can also pull one property out of each object, which is how map is used most often with Day 7’s arrays of objects:
type Product = { name: string; price: number };
const products: Product[] = [
{ name: "Pen", price: 2.5 },
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
];
const names = products.map((product) => product.name);
console.log(names);
console.log(names.join(", "));[ 'Pen', 'Backpack', 'Notebook' ]
Pen, Backpack, Notebook
Line 7 turns a Product[] into a string[] of names, and line 9 joins them with Day 3’s join. “Get the names of all the products” is one line, and it reads the way you would say it.
Key idea
items.map(callback) calls the callback on every element and gives back a new array of the results, in the same order
and of the same length. The element type of the new array is whatever the callback returns.
Watch out
A block body that never returns. When the callback needs more than one line, you write a block body with braces, and then, as Day 8 taught, nothing is returned unless you write return:
const words = ["map", "filter", "reduce"];
const lengths: number[] = words.map((word) => {
word.length;
});
console.log(lengths);map-no-return.ts:2:7 - error TS2322: Type 'void[]' is not assignable to type 'number[]'.
Type 'void' is not assignable to type 'number'.word.length; on line 3 works out a value and throws it away. The callback returns nothing, so its return type is void (Day 8), and map builds a void[]. The checker catches it here only because line 2 has an annotation. Without the annotation, npx tsc accepts the program, and node shows what void looks like at runtime:
const words = ["map", "filter", "reduce"];
const lengths = words.map((word) => {
word.length;
});
console.log(lengths);[ undefined, undefined, undefined ]Three elements went in, three undefineds came out. Either write return word.length; inside the braces, or drop the braces: (word) => word.length. Fix or delete map-no-return.ts before your next check.
Pause and try
Question 1 · Tracing
Predict exactly what this program shows, and the type of warm.
const temps = [20, 25, 30];
const fahrenheit = temps.map((c) => c * 1.8 + 32);
const warm = temps.map((c) => c > 22);
console.log(fahrenheit);
console.log(warm);
console.log(temps);Check your reasoning
[ 68, 77, 86 ]
[ false, true, true ]
[ 20, 25, 30 ]- Line 2: each Celsius value becomes
c * 1.8 + 32: 20 → 68, 25 → 77, 30 → 86. - Line 3: the callback returns a comparison, so each element becomes a boolean, and
warmis aboolean[]:20 > 22isfalse, the other two aretrue. - Line 6:
tempshas not changed.mapnever changes the array it is called on.
Reread 11.1 map: A New Array from Every Element if any line differed.
11.2 How the Checker Types the Callback
Look again at (price) => price * 1.2. On Day 8, every parameter had an annotation: (n: number): number => n * n. Here price has none, and yet npx tsc was happy, and price * 1.2 was allowed even though * on a string would be a type error. Where did the checker get the type of price?
From the array. prices is a number[], so map on it promises to call its callback with a number. The checker reads that promise and gives price the type number before it looks at the body. A parameter typed from the place a function is used, rather than from an annotation, is said to be contextually typed. Hover over price in VS Code and it shows (parameter) price: number, exactly as if you had written the annotation.
Worked example: With and without annotations
const scores = [72, 95, 58];
const curved = scores.map((score) => score + 5);
const curvedToo = scores.map((score: number): number => score + 5);
console.log(curved);
console.log(curvedToo);[ 77, 100, 63 ]
[ 77, 100, 63 ]Lines 2 and 3 mean the same thing. On line 3, score: number repeats what the checker already knew, and : number after the parentheses repeats what it can see from score + 5. Neither is wrong, but neither helps, and the extra words make the pipeline harder to read. This course writes callbacks without annotations whenever the array already fixes the type, which is nearly always.
Because the type comes from the array, a callback that treats the element as something else is caught at once:
const scores = [72, 95, 58];
const shouted = scores.map((score) => score.toUpperCase());
console.log(shouted);callback-wrong-method.ts:2:45 - error TS2339: Property 'toUpperCase' does not exist on type 'number'.
score is a number, numbers have no toUpperCase, and the message says so: TS2339 is the “no such property” message from Day 7, pointing at column 45, the method name. Now the other way round, an annotation that contradicts the array:
const scores = [72, 95, 58];
const lengths = scores.map((score: string) => score.length);
console.log(lengths);callback-wrong-annotation.ts:2:28 - error TS2345: Argument of type '(score: string) => number' is not assignable to parameter of type '(value: number, index: number, array: number[]) => number'.
Types of parameters 'score' and 'value' are incompatible.
Type 'number' is not assignable to type 'string'.
This message is longer, and worth taking apart, because every array method gives a message shaped like it:
| Part of the message | What it means |
|---|---|
Argument of type '(score: string) => number' |
The type of the callback you passed, as a function type from Day 10 |
is not assignable to parameter of type |
It does not fit what map asked for, which comes next |
'(value: number, index: number, array: number[]) => …' |
What map asked for: a function that accepts a number first |
| The two indented lines below it in the terminal | The exact mismatch: score was declared string, but will get a number |
The second part also reveals that map offers the callback three arguments, not one: the element (value), its position (index), and the whole array. A callback may declare as many of these as it needs, from the left. So far every callback has declared just the first. Declaring two gives you the index, which replaces Day 6’s entries() for this job:
const steps = ["Preheat the oven", "Mix the batter", "Bake for 25 minutes"];
const numbered = steps.map((step, index) => `${index + 1}. ${step}`);
console.log(numbered.join("\n"));1. Preheat the oven
2. Mix the batter
3. Bake for 25 minutes
index is contextually typed as number, and index + 1 turns the positions 0, 1, 2 into the numbers people expect. Fix or delete the two broken files from this subsection before you go on.
Key idea
A callback’s parameters are typed from the array: on a number[], every method calls its callback with a number.
You need no annotation, and a callback that treats the element as another type is rejected. The callback may also
declare a second parameter for the index.
Pause and try
Question 2 · Tracing
Predict exactly what this program shows, and the type the checker gives name in each callback.
const names = ["ada", "grace", "linus"];
const initials = names.map((name) => name[0].toUpperCase());
const tagged = names.map((name, i) => `${name}-${i}`);
const lengths = names.map((name) => name.length);
console.log(initials, tagged, lengths);Check your reasoning
[ 'A', 'G', 'L' ] [ 'ada-0', 'grace-1', 'linus-2' ] [ 3, 5, 5 ]names is a string[], so name is a string in all three callbacks, which is why name[0], .toUpperCase(), and .length are all allowed.
- Line 2: the first character of each name, in capitals.
- Line 3: the second parameter,
i, is the index, 0, 1, 2. - Line 4: the callback returns a number, so
lengthsis anumber[].
Reread 11.2 How the Checker Types the Callback if any line differed.
Question 3 · Multiple choice
const ages = [31, 25]; is followed by ages.map((age) => age.trim());. What happens?
npx tscreports TS2339:trimdoes not exist on typenumbernpx tscreports TS7006:ageimplicitly has ananytypenpx tscaccepts it, andnodeshows[ 31, 25 ]npx tscaccepts it, andnodestops with aTypeError
Check your reasoning
A. ages is a number[], so age is contextually typed as number, and numbers have no trim method. The checker reports the missing property before anything runs.
- B is wrong: the “implicitly any” message appears when the checker has no way to know a parameter’s type. Here the array tells it.
- C and D are wrong because the program never gets to
node: the check fails first. (If it did run, D would be right, which is exactly the crash the checker prevents.)
Reread 11.2 How the Checker Types the Callback if you chose differently.
11.3 filter: Keeping the Elements That Pass
map keeps every element and changes each one. The next most common loop keeps the elements that pass a test and leaves the rest out: the products under $20, the students who passed, the words with no vowels. As a loop, that is for...of with an if and a push:
type Product = { name: string; price: number };
const products: Product[] = [
{ name: "Pen", price: 2.5 },
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
];
const cheap: Product[] = [];
for (const product of products) {
if (product.price < 20) {
cheap.push(product);
}
}
console.log(cheap);[ { name: 'Pen', price: 2.5 }, { name: 'Notebook', price: 4 } ]
items.filter(callback) calls the callback once for each element and gives back a new array containing only the elements for which the callback returned a truthy value (Day 4’s truthy: usually simply true). A function that answers a yes-or-no question about a value like this is called a predicate.
Worked example: Cheap products with filter
type Product = { name: string; price: number };
const products: Product[] = [
{ name: "Pen", price: 2.5 },
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
];
const cheap = products.filter((product) => product.price < 20);
console.log(cheap);
console.log(cheap.length, products.length);[ { name: 'Pen', price: 2.5 }, { name: 'Notebook', price: 4 } ]
2 3| Call | product.name |
product.price < 20 |
Kept? |
|---|---|---|---|
| 1 | Pen | true |
Yes |
| 2 | Backpack | false |
No |
| 3 | Notebook | true |
Yes |
Two differences from map. First, the elements come through unchanged: cheap holds the very same product objects, not copies, so its type is Product[], the same as products. Second, the new array can be shorter: here two of three, as line 9 shows, and it would be empty if nothing passed.
Now vary the test. Any predicate works, including one that nothing passes:
const words = ["sun", "cloud", "rain", "snowstorm"];
const long = words.filter((word) => word.length > 4);
const withZ = words.filter((word) => word.includes("z"));
console.log(long);
console.log(withZ);[ 'cloud', 'snowstorm' ]
[]
Line 3 finds no word containing z, so withZ is an empty array, printed as []. That is not an error: an empty result is the correct answer to “which words contain a z?”. Code that uses the result must be ready for a length of 0, which a for...of over it already is, because the loop body simply never runs.
Key idea
items.filter(predicate) gives back a new array holding only the elements for which the predicate returned a truthy
value. The elements themselves are unchanged, the type stays the same, and the result may be shorter or empty.
Watch out
Using filter to change elements. The callback’s answer decides keep or drop; it is not stored:
const prices = [4, 0, 2.5];
const withTax = prices.filter((price) => price * 1.2);
console.log(withTax);[ 4, 2.5 ]The writer wanted the prices with tax, as in 11.1. But filter only asks “is price * 1.2 truthy?”. For 4 and 2.5 it is, so they are kept as they were; for 0 it is 0, which is falsy, so the free item is dropped. Neither npx tsc nor node reports anything, because a number is an allowed answer. When you want each element changed, use map; when you want some elements kept, use filter.
Pause and try
Question 4 · Tracing
Predict exactly what this program shows.
const ages = [12, 17, 18, 25, 64, 70];
const adults = ages.filter((age) => age >= 18);
const teens = ages.filter((age) => age >= 13 && age <= 19);
const centenarians = ages.filter((age) => age >= 100);
console.log(adults);
console.log(teens);
console.log(centenarians, centenarians.length);Check your reasoning
[ 18, 25, 64, 70 ]
[ 17, 18 ]
[] 0- Line 2: the ages that are at least 18, in their original order.
- Line 3: a range test with
&&, as on Day 4: only 17 and 18 are from 13 to 19. - Line 4: nobody is 100 or over, so the result is an empty array, whose length is 0. No error: an empty answer is still an answer.
Reread 11.3 filter: Keeping the Elements That Pass if any line differed.
11.4 find and findIndex
filter gives you every element that passes. Often you want just one: the product with this name, the first score below the pass mark. You could filter and take element 0, but that keeps testing after the answer is found, and element 0 of an empty array is a problem you met on Day 6.
items.find(predicate) calls the predicate on each element in turn and gives back the first element for which it returns a truthy value, stopping there. If no element passes, it gives back undefined. So its result type is a union from Day 9: for a Product[], find gives Product | undefined, and the checker makes you deal with the undefined case before you touch the result.
Worked example: Looking up a product by name
type Product = { name: string; price: number };
const products: Product[] = [
{ name: "Pen", price: 2.5 },
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
];
const wanted: string = "Notebook";
const found = products.find((product) => product.name === wanted);
if (found === undefined) {
console.log(`No product named ${wanted}`);
} else {
console.log(`${found.name} costs $${found.price.toFixed(2)}`);
}
console.log(products.find((product) => product.price > 100));Notebook costs $4.00
undefinedLine 8 asks for the first product whose name is wanted. The predicate is called for Pen (false), Backpack (false), and Notebook (true), and find stops and gives back that object. Hover over found: its type is Product | undefined. Line 9 narrows it with === undefined, exactly as Day 9 taught, so inside the else block found is a Product and found.price is allowed. Line 14 asks for a product over $100; none passes, so find gives undefined, which is what Node prints.
Sometimes you need the position of the element rather than the element itself, for example to remove it with Day 6’s splice. items.findIndex(predicate) works like find but gives back the index of the first match, or -1 when nothing matches, the same signal Day 3’s indexOf uses. Compare it with indexOf from Day 6: indexOf needs the exact value to look for; findIndex takes a test.
const scores = [72, 45, 95, 58];
const firstFail = scores.find((score) => score < 60);
const where = scores.findIndex((score) => score < 60);
const missing = scores.findIndex((score) => score > 100);
console.log(firstFail, where, missing);
console.log(scores.indexOf(95), scores.findIndex((score) => score === 95));45 1 -1
2 2
Line 2 gives the first failing score, 45, and line 3 its index, 1. Both stop at 45 and never look at 58, the second failing score; find and findIndex are about the first match only. Line 4 finds nothing, so the index is -1. Line 6 shows indexOf(95) and findIndex((score) => score === 95) agree; the second form only earns its keep when the test is more than “equals this value”.
Key idea
find gives back the first element that passes the predicate, or undefined; its type is T | undefined, so narrow
it before using it. findIndex gives the index of the first match, or -1.
Watch out
Using the result of find without checking it. The checker will not let you:
const scores = [72, 95, 58];
const failing = scores.find((score) => score < 60);
console.log(failing.toFixed(1));find-unchecked.ts:3:13 - error TS18048: 'failing' is possibly 'undefined'.TS18048 is Day 9’s message: failing is number | undefined, and undefined.toFixed(1) would crash at runtime, so the checker stops you first. Narrow it: if (failing !== undefined), or use Day 9’s ?? to supply a default, (failing ?? 0).toFixed(1). Fix or delete the file before your next check.
Pause and try
Question 5 · Tracing
Predict exactly what this program shows.
const words = ["kiwi", "apple", "fig", "banana"];
const short = words.find((word) => word.length <= 3);
const longIndex = words.findIndex((word) => word.length > 5);
const none = words.find((word) => word.startsWith("z"));
console.log(short, longIndex, none);
console.log(short?.toUpperCase() ?? "none");Check your reasoning
fig 3 undefined
FIG- Line 2:
"kiwi"and"apple"are longer than 3 characters;"fig"is the first that is not, soshortis"fig". - Line 3: the first word longer than 5 characters is
"banana", at index 3. - Line 4: no word starts with
z, sononeisundefined. - Line 6:
shortisstring | undefined, so the program uses Day 9’s?.and??.shortis a string, soshort?.toUpperCase()is"FIG", and??keeps it.
Reread 11.4 find and findIndex if any line differed.
Question 6 · Multiple choice
const scores = [72, 95, 58]; is followed by const index = scores.findIndex((s) => s > 100);. What is index, and what is its type?
undefined, of typenumber | undefined-1, of typenumber0, of typenumber- Nothing:
npx tscreports TS18048
Check your reasoning
B. No score is over 100, and findIndex signals “not found” with -1, like indexOf. Because -1 is a number, the result type is plain number, and no narrowing is needed before arithmetic.
- A is wrong:
undefinedis whatfindgives for no match, notfindIndex. - C is wrong: 0 would mean “the first element matched”, and 72 is not over 100.
- D is wrong: TS18048 is about
find’sT | undefinedresult;findIndexnever givesundefined.
Reread 11.4 find and findIndex if you chose differently.
11.5 some and every
Two questions about a whole array come up constantly: “does any element pass this test?” and “does every element pass it?”. On Day 5 you answered them with a boolean flag and a loop. Two methods answer them directly, and both give back a plain boolean.
items.some(predicate) is true when the predicate returns a truthy value for at least one element. It stops at the first one that does, like || short-circuiting. items.every(predicate) is true when the predicate returns a truthy value for all of them, and stops at the first that does not, like &&.
Worked example: Checking a week of temperatures
const temps = [18, 24, 31, 27];
const anyHot = temps.some((temp) => temp > 30);
const allMild = temps.every((temp) => temp >= 15 && temp <= 30);
const allAboveZero = temps.every((temp) => temp > 0);
console.log(anyHot, allMild, allAboveZero);true false true| Line | Question | Stops at | Result |
|---|---|---|---|
| 2 | Is any temperature over 30? | 31, the third element | true |
| 3 | Are all from 15 to 30? | 31 fails, so it stops there | false |
| 4 | Are all above zero? | Never: all four pass | true |
Line 3 shows every giving up early: once 31 fails, the answer cannot be true, so 27 is never tested. Compare line 2 with includes from Day 6: includes(31) asks whether one exact value is present; some((temp) => temp > 30) asks whether anything meets a condition.
Now vary the array: make it empty. The answers surprise most people the first time:
const noScores: number[] = [];
console.log(noScores.every((score) => score >= 60));
console.log(noScores.some((score) => score >= 60));true
false
With no elements, every never finds one that fails, so it is true: every score in an empty list is at least 60, because there is no score that is not. And some never finds one that passes, so it is false. This is the only consistent rule (adding an element that passes should never turn every from true to false), but it means “did everyone pass?” is true for a class with no students. When that matters, check length first.
Key idea
some(predicate) is true when at least one element passes; every(predicate) is true when all of them do. On an
empty array, every is true and some is false.
Watch out
Reaching for includes when the test is not exact equality. includes compares with ===, so case, spaces, and anything else must match exactly:
const guests = ["Ana", "Ben", "Chen"];
console.log(guests.includes("ana"));
console.log(guests.some((guest) => guest.toLowerCase() === "ana"));false
true"ana" is not strictly equal to "Ana", so line 2 is false. Line 3 states the real question, “is any guest called Ana, ignoring case?”, with some and Day 3’s toLowerCase. Whenever your test is anything but “equals this value”, includes is the wrong tool.
Pause and try
Question 7 · Tracing
A shop keeps the stock count of four items. Predict exactly what this program shows.
const stock = [3, 0, 12, 7];
console.log(stock.some((count) => count === 0));
console.log(stock.every((count) => count > 0));
console.log(stock.every((count) => count < 20));
console.log(stock.some((count) => count > 20));Check your reasoning
true
false
true
false- Line 2: is anything sold out? The second element is 0: true.
- Line 3: is everything in stock? The same 0 fails, so false;
everystops there. - Line 4: are all counts under 20? 3, 0, 12, and 7 all are: true.
- Line 5: is any count over 20? None: false.
Reread 11.5 some and every if any line differed.
11.6 reduce: Folding an Array into One Value
Day 5’s accumulator pattern builds one value from many: a total, a count, the longest word. The variable declared before the loop collects the answer, and each pass through the loop updates it:
const scores = [72, 95, 58];
let total = 0;
for (const score of scores) {
total = total + score;
}
console.log(total);225
There is a method for this too, and it is the one students find hardest to read at first, so take it slowly. items.reduce(callback, start) keeps one running value, called the accumulator. It begins as start. Then, for each element, it calls the callback with two arguments, the current accumulator and the element, and whatever the callback returns becomes the new accumulator. When the elements run out, reduce gives back the final accumulator.
Worked example: A total with reduce
const scores = [72, 95, 58];
const total = scores.reduce((sum, score) => sum + score, 0);
console.log(total);
console.log(total / scores.length);225
75The callback on line 2 is (sum, score) => sum + score: sum is the accumulator, score is the element, and the sum of the two is the next accumulator. The starting value is 0, the last argument.
| Call | sum (accumulator in) |
score |
Returns (accumulator out) |
|---|---|---|---|
| 1 | 0 | 72 | 72 |
| 2 | 72 | 95 | 167 |
| 3 | 167 | 58 | 225 |
Compare the table with sum-loop.ts: sum plays the part of total, the callback body is the loop body, and 0 is the starting value. Line 4 divides by the length to get the average; the Day 12 project will use exactly this.
The accumulator does not have to be a number, and the callback does not have to add. Here it keeps the longest word seen so far, and then counts letters:
const words = ["sun", "cloud", "rain", "snowstorm"];
const longest = words.reduce(
(best, word) => (word.length > best.length ? word : best),
"",
);
const letters = words.reduce((count, word) => count + word.length, 0);
console.log(longest, letters);snowstorm 21
Lines 2 to 5 start with the empty string, and each call returns whichever is longer, the best so far or the current word; the parentheses around the conditional operator are not required, but they make it easy to see where the returned value begins and ends. Line 6 is a sum again, but of word.length rather than of the elements themselves. In both, the type of the accumulator is the type of the starting value: a string for "", a number for 0.
That last sentence is the key to using reduce with objects. Suppose you want the total spent per category, as a Record<string, number> from Day 7. The natural starting value is an empty object, {}:
type Expense = { category: string; amount: number };
const expenses: Expense[] = [
{ category: "food", amount: 12.5 },
{ category: "travel", amount: 30 },
{ category: "food", amount: 7.5 },
];
const totals = expenses.reduce((sums, expense) => {
sums[expense.category] = (sums[expense.category] ?? 0) + expense.amount;
return sums;
}, {});
console.log(totals);totals-untyped.ts:8:3 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
totals-untyped.ts:8:29 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
The checker took the type of the accumulator from the starting value, and the type of {} is “an object with no properties at all”. You cannot look up sums["food"] in an object that has no properties, so line 8 is rejected (both the read on the right and the write on the left; the terminal shows two messages for the same line, at columns 3 and 29). The fix is to tell the checker what the accumulator will become: annotate the accumulator parameter, and the checker uses that type for the starting value too. (Another way to type the starting value is to store it in an annotated variable first, const start: Record<string, number> = {};, and pass start as the last argument.)
type Expense = { category: string; amount: number };
const expenses: Expense[] = [
{ category: "food", amount: 12.5 },
{ category: "travel", amount: 30 },
{ category: "food", amount: 7.5 },
];
const totals = expenses.reduce((sums: Record<string, number>, expense) => {
sums[expense.category] = (sums[expense.category] ?? 0) + expense.amount;
return sums;
}, {});
console.log(totals);
console.log(totals.food);{ food: 20, travel: 30 }
20
On line 7, sums: Record<string, number> is the one annotation in this program that does real work. Now sums[expense.category] is allowed. The body uses a block with return sums; at the end, because it must do two things: update one total, then hand the same object back as the next accumulator. ?? 0 handles a category seen for the first time: nothing is stored under it yet, so the lookup gives undefined, and Day 9’s ?? turns that into 0 before the amount is added. Fix or delete totals-untyped.ts before your next check.
Key idea
reduce(callback, start) runs the accumulator through the callback once per element, (accumulator, element) => newAccumulator, and gives back the final accumulator. The accumulator’s type comes from the starting value; when the
start is {}, annotate the accumulator parameter with the type it will become.
Watch out
Leaving out the starting value. scores.reduce((sum, score) => sum + score) is allowed: reduce then uses the first element as the starting accumulator and begins the callback at the second. For a sum of numbers that gives the same answer. But it fails in two ways. The accumulator is then forced to have the element’s type, so you cannot build a string or an object from numbers. And on an empty array there is no first element, so node stops with TypeError: Reduce of empty array with no initial value. Always pass a starting value.
Pause and try
Question 8 · Tracing
Predict exactly what this program shows. Write out each accumulator for the first reduce.
const steps = [3, -1, 4];
const position = steps.reduce((where, step) => where + step, 10);
const product = steps.reduce((acc, step) => acc * step, 1);
const sentence = ["to", "be", "or"].reduce((text, word) => `${text} ${word}`, "");
console.log(position, product);
console.log(`[${sentence}]`);Check your reasoning
16 -12
[ to be or]| Call | where in |
step |
where out |
|---|---|---|---|
| 1 | 10 | 3 | 13 |
| 2 | 13 | -1 | 12 |
| 3 | 12 | 4 | 16 |
- Line 3: a product, starting at 1: 1 × 3 = 3, 3 × −1 = −3, −3 × 4 = −12.
- Line 4: the accumulator is a string, starting empty. Each call adds a space and a word, so the result begins with a space:
" to be or". The brackets on line 6 make that leading space visible.
Reread 11.6 reduce: Folding an Array into One Value if any line differed.
Question 9 · Multiple choice
Kai writes words.reduce((counts, word) => { counts[word] = 1; return counts; }, {}) to build a Record<string, number>, and npx tsc reports TS7053 on counts[word]. What is the cause?
reduceneeds the starting value first and the callback second- The accumulator’s type came from
{}, which has no properties to look up countsshould be declared withletbecause it changes- A callback with a block body cannot be used with
reduce
Check your reasoning
B. The checker types the accumulator from the starting value, and {} is an object with no properties, so indexing it by a string is rejected. Annotate the accumulator parameter, (counts: Record<string, number>, word) => …, and the lookup is allowed.
- A is wrong: the callback comes first and the starting value second, as Kai wrote.
- C is wrong: parameters are never declared with
let, and changing an object’s properties does not need reassignment. - D is wrong: a block body is fine, and is needed here so that the callback can both update and
return counts.
Reread 11.6 reduce: Folding an Array into One Value if you chose differently.
11.7 sort with a Comparator
Sorting is the one job in this lesson that every program seems to need and that JavaScript gets wrong by default. items.sort() puts the elements of an array in order, changing the array itself. Called with no arguments, it has one rule: convert every element to a string, and compare the strings character by character, as Day 4’s < does. Watch what that does to numbers:
const ranks = [10, 9, 100, 1];
ranks.sort();
console.log(ranks);
const names = ["Zoe", "ana", "Ben"];
names.sort();
console.log(names);[ 1, 10, 100, 9 ]
[ 'Ben', 'Zoe', 'ana' ]
10 comes before 9 because, as strings, "1" comes before "9", the same surprise as "10" < "9" in 4.1. The names are in order, but it is character-code order, so every capital letter comes before every small one, and "ana" goes last. Neither npx tsc nor node complains; the array is sorted, just not the way a person would sort it.
To sort your way, pass sort a comparator: a callback that takes two elements, a and b, and returns a number that says which should come first. The contract is:
| The comparator returns | Meaning |
|---|---|
| A negative number | a comes before b |
| A positive number | b comes before a |
0 |
They are equal; keep their current order |
sort calls the comparator on pairs of elements as many times as it needs to, and arranges the array to agree with every answer. For numbers, the comparator writes itself: a - b is negative exactly when a is smaller.
Worked example: Sorting numbers as numbers
const ranks = [10, 9, 100, 1];
ranks.sort((a, b) => a - b);
console.log(ranks);
ranks.sort((a, b) => b - a);
console.log(ranks);[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]Line 2’s comparator, (a, b) => a - b, says “the smaller one first”: for the pair 10 and 9, 10 - 9 is positive, so 9 goes before 10. That gives ascending order. Line 4 swaps the subtraction, b - a, so the larger one comes first: descending. Both parameters are contextually typed as number from the array, as in 11.2.
Objects need a comparator that says which property to compare, and here Day 10’s function types keep things tidy:
type Product = { name: string; price: number };
type Comparator = (a: Product, b: Product) => number;
const products: Product[] = [
{ name: "Pen", price: 2.5 },
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
];
const byPrice: Comparator = (a, b) => a.price - b.price;
const byName: Comparator = (a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
};
products.sort(byPrice);
console.log(products.map((product) => product.name));
products.sort(byName);
console.log(products.map((product) => product.name));[ 'Pen', 'Notebook', 'Backpack' ]
[ 'Backpack', 'Notebook', 'Pen' ]
Line 2 names the comparator type once, and lines 8 and 9 give two comparators that type. byPrice subtracts prices. byName cannot subtract strings, so it uses Day 4’s string comparison in an if chain: -1 when a.name comes first, 1 when b.name does, 0 otherwise. It is longer, but it follows the contract to the letter, and you can read every case. (Strings also have a localeCompare method that returns exactly such a number, ordering letters the way a dictionary does regardless of case; (a, b) => a.name.localeCompare(b.name) is the usual short form.) Line 18 sorts the products in place, and line 19 maps the sorted array to names so the output is readable.
Key idea
sort() with no comparator sorts as strings, which puts 10 before 9. Pass a comparator (a, b) => … that returns
a negative number to put a first, positive to put b first, and 0 for equal: a - b for ascending numbers.
Watch out
A comparator that returns a boolean. It is tempting to write the comparison you have in mind:
const ranks = [10, 9, 100, 1];
ranks.sort((a, b) => a > b);
console.log(ranks);sort-boolean.ts:2:12 - error TS2345: Argument of type '(a: number, b: number) => boolean' is not assignable to parameter of type '(a: number, b: number) => number'.
Type 'boolean' is not assignable to type 'number'.The message is the shape you met in 11.2: sort asked for a function returning a number, and a > b returns a boolean. A boolean cannot say “equal”, and true and false do not tell sort which way round to put the pair. Return a - b instead, and fix or delete this file before your next check.
Pause and try
Question 10 · Tracing
Predict exactly what this program shows. Each line sorts a fresh copy made with Day 6’s spread.
const times = [95, 120, 7, 1000];
console.log([...times].sort());
console.log([...times].sort((a, b) => a - b));
console.log([...times].sort((a, b) => b - a));
console.log(times);Check your reasoning
[ 1000, 120, 7, 95 ]
[ 7, 95, 120, 1000 ]
[ 1000, 120, 95, 7 ]
[ 95, 120, 7, 1000 ]- Line 2: no comparator, so the numbers are compared as strings:
"1000","120","7","95"."1000"comes before"120"because the second characters are"0"and"2". - Line 3:
a - bgives ascending numeric order. - Line 4:
b - agives descending order. - Line 5: each sort worked on a copy, so
timesis unchanged.
Reread 11.7 sort with a Comparator if any line differed.
Question 11 · Multiple choice
Which comparator sorts an array of { name: string; age: number } objects from oldest to youngest?
(a, b) => a.age - b.age(a, b) => b.age - a.age(a, b) => a.age > b.age(a, b) => b.age
Check your reasoning
B. Oldest first means the larger age comes first, and b.age - a.age is negative exactly when b is younger than a, which puts a first when a is older.
- A is wrong:
a.age - b.ageis ascending, youngest first. - C is wrong: it returns a boolean, and
npx tscrejects it with TS2345. - D is wrong: it ignores
aentirely and is always positive (for real ages), which tellssortnothing consistent.
Reread 11.7 sort with a Comparator if you chose differently.
11.8 Copying Methods Versus Changing Methods
Look back at sort-products.ts: after line 18, products itself is in price order. sort is like Day 6’s push: it changes the array it is called on. map, filter, and slice, on the other hand, leave the array alone and give back a new one. Knowing which methods do which is the difference between a program that works and one whose data quietly rearranges itself.
Worked example: sort changes the array it is called on
const scores = [72, 95, 58];
const sorted = scores.sort((a, b) => a - b);
console.log(sorted);
console.log(scores);
console.log(sorted === scores);[ 58, 72, 95 ]
[ 58, 72, 95 ]
truesort does give back an array, which line 2 stores in sorted, and that misleads people into thinking it made a copy. Line 5 shows the truth: sorted === scores is true, meaning both names refer to the same array, the one scores always held, which is now in a different order. The original order is gone.
Modern JavaScript has copying twins for the changing methods. toSorted(comparator) does what sort does, but on a new array, leaving the original as it was. Likewise toReversed() copies and reverses, where reverse() reverses in place, and toSpliced is the copying twin of Day 6’s splice: it takes the same arguments and gives back a new array with the change made.
const scores = [72, 95, 58];
const sorted = scores.toSorted((a, b) => a - b);
const backwards = scores.toReversed();
console.log(sorted);
console.log(backwards);
console.log(scores);
console.log(sorted === scores);[ 58, 72, 95 ]
[ 58, 95, 72 ]
[ 72, 95, 58 ]
false
Now scores keeps its order (line 6), and sorted === scores is false: two different arrays. Here is the full roll-call of the methods you know:
| Changes the array (in place) | Gives back a new array |
|---|---|
push, pop, shift, unshift |
slice, [...items] |
splice |
toSpliced |
sort, reverse |
toSorted, toReversed |
map, filter |
find, findIndex, some, every, and reduce belong to neither column: they change nothing and give back a single value, not an array. The checker can help you remember. Day 6’s readonly array rejects every method in the left column and allows every method in the right one:
const ranks: readonly number[] = [10, 9, 100, 1];
const sorted = ranks.toSorted((a, b) => a - b);
console.log(sorted);
ranks.sort();readonly-sort.ts:4:7 - error TS2339: Property 'sort' does not exist on type 'readonly number[]'.
Line 2 is accepted: toSorted makes a new array, so it cannot break the promise that ranks never changes. Line 4 is the same TS2339 you met for push on Day 6, and it tells you something useful: if a method is missing from a readonly array, it is a changing method. Fix or delete the file before your next check.
Key idea
sort, reverse, splice, and the push family change the array in place; toSorted, toReversed, toSpliced,
slice, map, and filter give back a new array and leave the original alone. A readonly array allows only the
copying ones.
Watch out
Sorting a parameter. Day 8 asked you to prefer pure functions, which do not change their arguments. sort inside a function breaks that promise for the caller:
function highest(scores: number[]): number {
return scores.sort((a, b) => b - a)[0];
}
const attempts = [72, 95, 58];
console.log(highest(attempts));
console.log(attempts);95
[ 95, 72, 58 ]The function gives the right answer, but line 6 shows the caller’s attempts, which were in the order they happened, have been reordered. Nothing reports this; the caller finds out later, when a “first attempt” display shows 95. A one-word change fixes it:
function highest(scores: number[]): number {
return scores.toSorted((a, b) => b - a)[0];
}
const attempts = [72, 95, 58];
console.log(highest(attempts));
console.log(attempts);95
[ 72, 95, 58 ]Inside a function, reach for toSorted and toReversed unless changing the caller’s array is the point of the function.
Pause and try
Question 12 · Tracing
Predict exactly what this program shows. Decide for each method whether it changes queue or copies it.
const queue = ["Ana", "Ben", "Chen"];
const reversed = queue.toReversed();
const shouted = queue.map((name) => name.toUpperCase());
queue.push("Dev");
queue.reverse();
console.log(queue);
console.log(reversed);
console.log(shouted);Check your reasoning
[ 'Dev', 'Chen', 'Ben', 'Ana' ]
[ 'Chen', 'Ben', 'Ana' ]
[ 'ANA', 'BEN', 'CHEN' ]- Line 2:
toReversedcopies, soreversedis a new three-element array in reverse order, andqueueis untouched. - Line 3:
mapcopies too;shoutedhas the three names in capitals. - Line 4:
pushchangesqueue, which now has four names. - Line 5:
reversechangesqueuein place: Dev, Chen, Ben, Ana. - Lines 6 to 8:
queueshows the four reversed names;reversedandshoutedwere made before the push, from the original three, and are unaffected.
Reread 11.8 Copying Methods Versus Changing Methods if any line differed.
11.9 Chaining Methods into a Pipeline
Every copying method gives back an array, and an array has all these methods again. So you can call the next method directly on the result of the previous one, without naming the array in between. A series of calls like this is a pipeline: the array goes in at the top, each stage hands a new array to the next, and the answer comes out at the bottom.
Take a real job: from a list of scores, report the top three passing scores, highest first, as percentages. One stage per requirement:
Worked example: Top three passing scores
const scores = [72, 45, 95, 58, 88, 61];
const report = scores
.filter((score) => score >= 60)
.toSorted((a, b) => b - a)
.slice(0, 3)
.map((score) => `${score}%`)
.join(", ");
console.log(report);95%, 88%, 72%Read it top to bottom; each line starts with a dot and is one stage. Written with a named variable per stage, the same program shows what each stage hands on:
const scores = [72, 45, 95, 58, 88, 61];
const passing = scores.filter((score) => score >= 60);
const ordered = passing.toSorted((a, b) => b - a);
const topThree = ordered.slice(0, 3);
const labels = topThree.map((score) => `${score}%`);
console.log(passing);
console.log(ordered);
console.log(topThree);
console.log(labels);[ 72, 95, 88, 61 ]
[ 95, 88, 72, 61 ]
[ 95, 88, 72 ]
[ '95%', '88%', '72%' ]| Stage | Gives | Type |
|---|---|---|
filter(score >= 60) |
[72, 95, 88, 61] |
number[] |
toSorted(b - a) |
[95, 88, 72, 61] |
number[] |
slice(0, 3) |
[95, 88, 72] |
number[] |
map(`${score}%`) |
["95%", "88%", "72%"] |
string[] |
join(", ") |
"95%, 88%, 72%" |
string |
The checker follows the type through every stage, so inside the map callback it still knows score is a number, and after the map it knows the elements are strings. join ends the pipeline with a string, so there is nothing to chain after it. The one-line-per-stage layout is what Prettier produces for a chain this long, and it is the layout to copy: a pipeline on one line is as hard to read as a paragraph with no full stops.
Which version should you write? The named-variable version is easier to debug, because you can print any stage. The chained version has no names to invent and reads as a single sentence: “the passing scores, highest first, the top three, as percentages, joined”. Start with the chain; break it up when you need to look inside.
Key idea
Because copying methods give back arrays, calls can be chained into a pipeline, one stage per line. The checker tracks
the element type through every stage. toSorted, not sort, belongs in a pipeline.
Watch out
Stages in the wrong order. Each stage sees only what the previous one handed on:
const names = ["ana", "Ben", "amir"];
const wrong = names
.map((name) => name.toUpperCase())
.filter((name) => name.startsWith("a"));
const right = names
.filter((name) => name.startsWith("a"))
.map((name) => name.toUpperCase());
console.log(wrong);
console.log(right);[]
[ 'ANA', 'AMIR' ]The writer wanted the names starting with a, in capitals. Lines 2 to 4 capitalize first, so by the time filter looks, every name starts with a capital letter and startsWith("a") is false for all of them: an empty result and no message. Lines 5 to 7 filter first, then capitalize. As a rule, filter early (there is less to process afterwards), map once the elements are what you want to keep, and toSorted when the elements have the shape you want to compare.
Pause and try
Question 13 · Tracing
Predict exactly what this program shows. Write down what each stage hands on.
const words = ["kiwi", "apple", "fig", "banana", "plum"];
const result = words
.filter((word) => word.length > 3)
.map((word) => word.length)
.toSorted((a, b) => a - b);
const total = result.reduce((sum, n) => sum + n, 0);
console.log(result, total);Check your reasoning
[ 4, 4, 5, 6 ] 19| Stage | Hands on |
|---|---|
filter(length > 3) |
["kiwi", "apple", "banana", "plum"] |
map(length) |
[4, 5, 6, 4] |
toSorted(a - b) |
[4, 4, 5, 6] |
reduce(sum, 0) on line 6 |
19 |
"fig" is the only word of 3 letters or fewer, so it is dropped first. After map, the elements are numbers, so toSorted needs the numeric comparator, which it has.
Reread 11.9 Chaining Methods into a Pipeline if any line differed.
11.10 Method or Loop?
You now have two ways to do everything in this lesson, and both are correct. for...of is not old-fashioned, and array methods are not always better. Each is the clearer choice for some jobs.
A method is a good fit when the job is one of the questions a method is named for. “A new array with each element changed” is map; “the ones that pass” is filter; “the first one that passes” is find; “is any”, “are all” are some and every; “one value built from all of them” is reduce. Code that uses the method says what it computes and nothing else, with no index, no empty array to declare, and no push to forget.
A loop is a good fit when the job does not match one of those names, in particular when:
- The body does more than one thing per element, such as printing and totalling at once.
- You need to stop early for a reason that is not “found it”:
breakafter three matches, for example. - You need two or more results from one pass, such as a total and a count.
- The loop is nested, like Day 5’s multiplication table.
Worked example: The same job, both ways
The total of the first three passing scores needs both “the ones that pass” and “stop after three”:
const scores = [72, 45, 95, 58, 88, 61];
const chained = scores
.filter((score) => score >= 60)
.slice(0, 3)
.reduce((sum, score) => sum + score, 0);
let looped = 0;
let taken = 0;
for (const score of scores) {
if (score >= 60) {
looped += score;
taken++;
if (taken === 3) {
break;
}
}
}
console.log(chained, looped);255 255Lines 2 to 5 are a pipeline: keep the passing scores, keep the first three, add them up. Lines 6 to 16 are a loop that counts how many it has taken and breaks at three. Both give 255. The chain is shorter and each stage is one idea, so most readers prefer it here. But if the task also needed to print each score as it was added, the loop would win, because that is a second thing to do per element.
A loop is also the right tool when the point is to do something for each element rather than to compute a result, such as printing a line per deposit:
const deposits = [50, 20, 35];
let balance = 0;
for (const [i, deposit] of deposits.entries()) {
balance += deposit;
console.log(`Deposit ${i + 1}: +${deposit}, balance ${balance}`);
}Deposit 1: +50, balance 50
Deposit 2: +20, balance 70
Deposit 3: +35, balance 105
Day 6’s entries() supplies the index and the element, the running balance is updated, and a line is printed, all in one pass. A pipeline would need map to carry the balance from one element to the next, which map cannot do, because each callback call sees only its own element.
You may meet one more method in other people’s code, forEach, which calls a callback for each element and returns nothing:
const guests = ["Ana", "Ben"];
guests.forEach((guest) => {
console.log(`Welcome, ${guest}!`);
});
for (const guest of guests) {
console.log(`Goodbye, ${guest}!`);
}Welcome, Ana!
Welcome, Ben!
Goodbye, Ana!
Goodbye, Ben!
The two halves do the same thing. This course prefers the for...of form: break and continue work in it, and there is no callback to wrap the body in. Use forEach only at the end of a pipeline, where the array has no name to loop over.
Key idea
Use a method when the job is the question it is named for: map, filter, find, some, every, reduce. Use
for...of when the body does several things, stops early, produces more than one result, or is nested.
Pause and try
Question 14 · Short answer
For each task, name the method you would reach for, or say “loop” and why: (a) the usernames that are longer than 12 characters; (b) is any order unpaid; (c) print a numbered receipt line for every item while keeping a running total; (d) the number of students who scored under 50; (e) the first product that is out of stock.
Check your reasoning
Model answer:
- (a)
filter: keep the ones that pass a test. - (b)
some: does at least one element pass. - (c) A loop: it prints and totals, two things per element, and the total carries from one element to the next.
- (d)
filterand then.length: count how many pass. (Areducethat adds 1 per failing score also works, but is harder to read.) - (e)
find: the first element that passes, remembering the result isT | undefined.
A complete answer matches each question to the method named for it and gives a loop reason for (c): more than one thing per element, or a value that must carry across elements.
Reread 11.10 Method or Loop? if you chose differently.
Putting it together
A game night keeps each player’s round scores. The program ranks the players who played by their average, highest first, prints an aligned leaderboard, and reports anyone who sat out. Before you type it, make sure npx tsc is clean in your day11 folder: fix or delete any broken file from today.
type Player = { name: string; rounds: number[] };
const players: Player[] = [
{ name: "Ana", rounds: [18, 22, 20] },
{ name: "Ben", rounds: [] },
{ name: "Chen", rounds: [25, 19, 24] },
{ name: "Dev", rounds: [21, 20, 17] },
];
const average = (rounds: number[]): number =>
rounds.length === 0 ? 0 : rounds.reduce((sum, r) => sum + r, 0) / rounds.length;
const ranked = players
.filter((player) => player.rounds.length > 0)
.map((player) => ({ name: player.name, average: average(player.rounds) }))
.toSorted((a, b) => b.average - a.average);
const lines = ranked.map(
(entry, i) => `${i + 1}. ${entry.name.padEnd(6)} ${entry.average.toFixed(1)}`,
);
console.log(lines.join("\n"));
const everyonePlayed = players.every((player) => player.rounds.length > 0);
const sitter = players.find((player) => player.rounds.length === 0);
console.log(everyonePlayed ? "Everyone played." : `${sitter?.name ?? "Someone"} sat out.`);npx tsc reports no errors, and node leaderboard.ts shows:
1. Chen 22.7
2. Ana 20.0
3. Dev 19.3
Ben sat out.
Follow the data through the program:
| Lines | What happens | Idea |
|---|---|---|
| 9–10 | average sums with reduce and divides; an empty list gives 0 rather than NaN |
11.6 |
| 13 | filter drops Ben, whose rounds is empty |
11.3 |
| 14 | map turns each player into { name, average }; the parentheses around the braces make the body an object, not a block |
11.1 |
| 15 | toSorted by average, descending, without touching players |
11.7, 11.8 |
| 17–19 | A second map with the index builds each line; padEnd is padStart’s twin and pads on the right |
11.2 |
| 22 | every asks whether all players have rounds: false, because of Ben |
11.5 |
| 23 | find gives Ben’s object, or undefined if everyone played |
11.4 |
| 24 | sitter is Player | undefined, so ?. and ?? from Day 9 read the name safely |
11.4 |
Line 14 holds one piece of new syntax: (player) => ({ … }). Braces straight after => would start a block body, so an arrow function that returns an object literal wraps it in parentheses. Each stage of the pipeline on lines 12 to 15 gives a new array, and players is never changed, which is why line 22 can still see Ben. Change Ben’s rounds to [20, 20, 20] and run it again: he joins the table in a tie with Ana, and the last line changes.
Common mistakes
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2339: Property 'toUpperCase' does not exist on type 'number'. |
The callback treats the element as another type | Check the array’s element type |
TS2345: Argument of type '(score: string) => number' is not assignable … |
A parameter annotation that contradicts the array | Drop the annotation |
TS2345: Argument of type '(a: number, b: number) => boolean' … |
A comparator returning a > b |
Return a - b |
TS2322: Type 'void[]' is not assignable to type 'number[]'. |
A block-body callback with no return |
Add return, or drop the braces |
TS18048: 'failing' is possibly 'undefined'. |
Using the result of find without narrowing |
if (x !== undefined) or ?? |
TS7053: Element implicitly has an 'any' type … index type '{}'. |
A reduce starting from {} with no accumulator type |
Annotate the accumulator parameter |
TS2339: Property 'sort' does not exist on type 'readonly number[]'. |
A changing method on a readonly array |
Use toSorted |
[ 1, 10, 100, 9 ] |
sort() with no comparator on numbers |
sort((a, b) => a - b) |
[ undefined, undefined ] from map |
No return in a block body |
Add return |
Elements unchanged after filter |
filter used where map was meant |
map changes; filter keeps |
| The original array is reordered | sort or reverse on an array someone else still uses |
toSorted, toReversed |
| An empty result from a pipeline | A stage changed what the next stage was testing | filter before map |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| callback | A function passed to a method, which calls it once per element | (price) => price * 1.2 |
| contextually typed | A parameter whose type comes from where the function is used, not from an annotation | price in prices.map((price) => …) |
| predicate | A callback that answers yes or no about one element | (age) => age >= 18 |
| accumulator | The running value reduce passes from one call to the next |
sum in (sum, score) => sum + score |
| comparator | A callback (a, b) returning negative, positive, or 0 to say which comes first |
(a, b) => a - b |
| in place | Changing the array a method is called on, rather than making a new one | sort, reverse, push |
| pipeline | A chain of method calls, each working on the array the previous one gave back | scores.filter(…).map(…).join(…) |
Summary
mapgives a new array with every element transformed;filtergives a new array with only the elements that pass a predicate;findgives the first one that passes, orundefined;findIndexgives its index, or -1;someandeverygive a boolean, and on an empty array arefalseandtrue.- A callback’s parameters are contextually typed from the array’s element type, so they need no annotations, and a callback that treats the element as another type is rejected.
reduce(callback, start)passes an accumulator through the callback once per element; its type comes from the starting value, so annotate the accumulator parameter when the start is{}.sort()without a comparator sorts as strings, putting10before9;(a, b) => a - bsorts numbers ascending.sortandreversechange the array in place;toSortedandtoReversedcopy.- Copying methods chain into a pipeline, one stage per line, and the checker follows the element type through every stage. Use a loop when the body does several things, stops early, or needs more than one result.
Practice
Do these in your day11 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (map-no-return.ts, callback-wrong-method.ts, callback-wrong-annotation.ts, find-unchecked.ts, totals-untyped.ts, sort-boolean.ts, or readonly-sort.ts), fix it or delete it. Then write each program yourself, check it with npx tsc, run it with node, and only then open the answer. Change the data and run again, including an array where nothing passes.
Question 15 · Short answer
Cheap products. Store an array of products, each with a name and a price, including at least one at exactly $20. Print the names of the products under $20, cheapest first, one per line with its price, and then show that the original array is still in its original order.
Check your reasoning
One possible solution:
type Product = { name: string; price: number };
const products: Product[] = [
{ name: "Backpack", price: 45 },
{ name: "Notebook", price: 4 },
{ name: "Water bottle", price: 19.99 },
{ name: "Pen", price: 2.5 },
{ name: "Headphones", price: 20 },
];
const cheapNames = products
.filter((product) => product.price < 20)
.toSorted((a, b) => a.price - b.price)
.map((product) => `${product.name} ($${product.price.toFixed(2)})`);
console.log(cheapNames.join("\n"));
console.log(products.map((product) => product.name));Pen ($2.50)
Notebook ($4.00)
Water bottle ($19.99)
[ 'Backpack', 'Notebook', 'Water bottle', 'Pen', 'Headphones' ]The pipeline filters first, so the sort only handles the cheap ones; toSorted with a.price - b.price puts the cheapest first without changing products; and map turns each remaining object into a line of text. Headphones at exactly $20 fail < 20, as the question required. The last line maps the original array to names and shows its order is untouched. Try <= 20, and try sorting by name instead.
Reread 11.9 Chaining Methods into a Pipeline and 11.7 sort with a Comparator if your result differed.
Question 16 · Short answer
Group by first letter. Store an array of words. Using reduce with a typed starting value, build a Record<string, string[]> whose keys are first letters and whose values are the words that start with that letter, in their original order. Print the record and its keys.
Check your reasoning
One possible solution:
const words = ["apple", "banana", "avocado", "blueberry", "cherry", "apricot"];
const groups = words.reduce((byLetter: Record<string, string[]>, word) => {
const letter = word[0];
if (byLetter[letter] === undefined) {
byLetter[letter] = [];
}
byLetter[letter].push(word);
return byLetter;
}, {});
console.log(groups);
console.log(Object.keys(groups));{
a: [ 'apple', 'avocado', 'apricot' ],
b: [ 'banana', 'blueberry' ],
c: [ 'cherry' ]
}
[ 'a', 'b', 'c' ]The accumulator parameter on line 2 is annotated Record<string, string[]>, which is what makes byLetter[letter] legal on a start of {}. For each word, line 4 checks whether its letter has a group yet; the first time, line 5 creates an empty one. Line 7 pushes the word, and line 8 hands the same object on as the next accumulator. (Node prints the record over several lines when it is too long for one.) Try adding a word with a capital first letter and decide whether toLowerCase belongs on line 3.
Reread 11.6 reduce: Folding an Array into One Value if your result differed.
Question 17 · Short answer
Did everyone pass? Store an array of students, each with a name and a score, and a pass mark. Print whether every student passed. Then find the first student who did not and print their name and score, or a message if there is nobody to find. Finally print how many are below the mark.
Check your reasoning
One possible solution:
type Student = { name: string; score: number };
const students: Student[] = [
{ name: "Ana", score: 82 },
{ name: "Ben", score: 58 },
{ name: "Chen", score: 91 },
{ name: "Dev", score: 49 },
];
const passMark = 60;
const allPassed = students.every((student) => student.score >= passMark);
console.log(allPassed ? "Everyone passed." : "Not everyone passed.");
const firstFail = students.find((student) => student.score < passMark);
if (firstFail === undefined) {
console.log("Nobody needs a retake.");
} else {
console.log(`First to retake: ${firstFail.name} (${firstFail.score})`);
}
console.log(students.filter((student) => student.score < passMark).length, "below the mark");Not everyone passed.
First to retake: Ben (58)
2 below the markevery on line 9 answers the yes-or-no question and feeds a conditional operator. find on line 11 gives Student | undefined, so line 12 narrows it before firstFail.name is read on line 15; without that if, the checker reports TS18048. Line 17 counts with filter(…).length. Change every score to 60 or more: every becomes true, find gives undefined, and the second message changes.
Reread 11.5 some and every and 11.4 find and findIndex if your result differed.
Review questions
Question 18 · Tracing
Predict exactly what this program shows.
const prices = [8, 15, 22, 3];
const discounted = prices.map((price) => price * 0.5);
const cheap = discounted.filter((price) => price < 5);
const count = prices.filter((price) => price > 10).map((price) => `$${price}`);
console.log(discounted);
console.log(cheap);
console.log(count);Check your reasoning
[ 4, 7.5, 11, 1.5 ]
[ 4, 1.5 ]
[ '$15', '$22' ]- Line 2: every price halved: 8 → 4, 15 → 7.5, 22 → 11, 3 → 1.5.
- Line 3: from the halved prices, those under 5: 4 and 1.5.
- Line 4: a two-stage pipeline on the original prices:
filterkeeps 15 and 22, thenmapmakes labels. Despite its name,countis astring[], not a number.
Reread 11.3 filter: Keeping the Elements That Pass and 11.9 Chaining Methods into a Pipeline if any line differed.
Question 19 · Debugging
This program should report the fastest finish time. npx tsc accepts it, but the output is wrong. Predict what it shows, explain why, and write the fix.
const finishTimes = [58, 102, 7, 65];
finishTimes.sort();
console.log(`Fastest: ${finishTimes[0]} seconds`);
console.log(finishTimes);Check your reasoning
Fastest: 102 seconds
[ 102, 58, 65, 7 ]With no comparator, sort compares the times as strings: "102" comes before "58" because "1" comes before "5", and "7" goes last. So element 0 is 102, the slowest. Nothing reports it, because sorting numbers as strings is allowed. Give sort a numeric comparator:
const finishTimes = [58, 102, 7, 65];
finishTimes.sort((a, b) => a - b);
console.log(`Fastest: ${finishTimes[0]} seconds`);
console.log(finishTimes);Fastest: 7 seconds
[ 7, 58, 65, 102 ]Reread 11.7 sort with a Comparator if you missed it.
Question 20 · Tracing
Predict exactly what this program shows. Trace the accumulator through all four votes.
const votes = ["yes", "no", "yes", "yes"];
const tally = votes.reduce((counts: Record<string, number>, vote) => {
counts[vote] = (counts[vote] ?? 0) + 1;
return counts;
}, {});
const yesCount = votes.filter((vote) => vote === "yes").length;
console.log(tally);
console.log(yesCount, tally.yes === yesCount);Check your reasoning
{ yes: 3, no: 1 }
3 true| Call | counts in |
vote |
counts out |
|---|---|---|---|
| 1 | {} |
yes | { yes: 1 } |
| 2 | { yes: 1 } |
no | { yes: 1, no: 1 } |
| 3 | { yes: 1, no: 1 } |
yes | { yes: 2, no: 1 } |
| 4 | { yes: 2, no: 1 } |
yes | { yes: 3, no: 1 } |
On the first call, counts["yes"] is undefined, and ?? 0 turns it into 0 before the 1 is added. yesCount counts the same votes with filter and length, so the two agree and the comparison is true.
Reread 11.6 reduce: Folding an Array into One Value if any line differed.
Question 21 · Short answer
Read this pipeline back into one English sentence that says what result holds, and give the number it prints.
type Book = { title: string; pages: number; read: boolean };
const books: Book[] = [
{ title: "Dune", pages: 412, read: true },
{ title: "Emma", pages: 474, read: false },
{ title: "Kim", pages: 306, read: true },
];
const result = books
.filter((book) => book.read)
.map((book) => book.pages)
.reduce((sum, pages) => sum + pages, 0);
console.log(result);Check your reasoning
Model answer: result is the total number of pages in the books that have been read. The filter keeps the two books with read: true (Dune and Kim), map replaces each with its page count (412 and 306), and reduce adds them from 0: 718.
A complete answer must name all three stages in order (keep the read books, take their page counts, add them up) and state the number 718.
Reread 11.9 Chaining Methods into a Pipeline if your sentence differed.
Question 22 · Tracing
items is an empty string[]. Predict exactly what this program shows.
const items: string[] = [];
console.log(items.map((item) => item.length));
console.log(items.find((item) => item === "a"));
console.log(items.every((item) => item === "a"), items.some((item) => item === "a"));
console.log(items.reduce((sum, item) => sum + item.length, 0));Check your reasoning
[]
undefined
true false
0- Line 2:
mapover nothing gives an empty array. - Line 3:
findhas no element to return, soundefined. - Line 4:
everyistrueon an empty array (nothing fails) andsomeisfalse(nothing passes). - Line 5:
reducenever calls its callback, so it gives back the starting value, 0. Without the starting value, this line would crash.
Reread 11.5 some and every and 11.6 reduce: Folding an Array into One Value if any line differed.
Question 23 · Multiple choice
const a = [3, 1, 2]; is followed by const b = a.toSorted((x, y) => x - y); and then const c = a.sort((x, y) => x - y);. Which statement is true after all three lines?
ais[3, 1, 2], andb === cistrueais[1, 2, 3], anda === cistrueais[1, 2, 3], anda === bistruenpx tscrejects the third line, becauseais aconst
Check your reasoning
B. toSorted made b as a separate array and left a alone. Then sort reordered a itself and gave back that same array, so c and a are the same array, now [1, 2, 3].
- A is wrong:
sortchangeda, andbandcare different arrays even though they hold the same values. - C is wrong:
toSortedalways makes a new array, soa === bisfalse. - D is wrong:
conststopsafrom being assigned a different array; it does not stop the array’s contents from changing, as Day 6 showed withpush.
Reread 11.8 Copying Methods Versus Changing Methods if you chose differently.
Go further
MDN’s Array reference describes every method in this lesson, with the exact arguments each callback receives and what each method returns: MDN: Array, iterative methods. The “Copying methods and mutating methods” section just above it is the full version of the table in 11.8.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can rewrite a loop that transforms every element as a map call. Reread
- I can say where a callback parameter gets its type and read the message when it is used as the wrong type. Reread
- I can keep the elements that pass a test with filter, and tell filter from map. Reread
- I can use find and findIndex, and narrow the T | undefined result of find. Reread
- I can answer "any?" and "all?" with some and every, including on an empty array. Reread
- I can trace a reduce call through its accumulator and type the starting value. Reread
- I can explain why sort() puts 10 before 9 and write a comparator that fixes it. Reread
- I can tell the methods that change an array from the ones that copy it. Reread
- I can chain methods into a pipeline and read one back in English. Reread
- I can decide when a for...of loop is clearer than a method. Reread