Put a list in order with sort, and avoid its three traps: with no rule it compares everything as text, so 10 comes before 5 and capitals jump ahead; it changes the list itself; and its rule must answer with a number. Write a compare function, (a, b) => a - b, sort words with localeCompare, keep the old order with toSorted, and make TaskKit print its list from A to Z.
Fundamentals
TypeScript
Sorting and its pitfalls. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
The last lesson ended with a promise about sort: it takes a rule
much like the ones you wrote there, and it changes the list you
call it on. Try it first with no rule at all. You note how long
each of today's tasks takes, 25, 15, 30 and 10 minutes, and
minutes.sort() puts them in order: 10, 15, 25, 30. The next day
you add a five-minute task, sort again, and get 10, 15, 25, 30, 5.
And the order you typed them in is gone, from the only list you
had.
Nothing is broken. With no rule, sort puts things in text
order: it turns every item into text and compares it one
character at a time. "ant" comes before "bee" however long each
word is, and in the same way "10" comes before "5", because "1"
comes before "5". By the end
of this lesson you hand sort a rule that says what "in order"
means, sort numbers and words the way you read them, keep the old
order when you still need it, and TaskKit prints its list from A
to Z.
sort puts the list itself in order
Start with words, where sort with no rule does what you expect.
Run this:
It prints the three tasks from A to Z. Now look at what is not
there: a new box. map and filter give back a new list and leave
the old one alone. sort moves the items around inside tasks
itself, the way push in lesson 4.1 added an item to it. const
does not stop it: const locks which list is in the box, not the
order of the items inside.
Often that is fine. But sometimes the old order still means
something: the order the tasks were added, or the order a teacher
read the names out. For that, a list has a second method,
toSorted. It sorts like sort, and gives back a new list in a
box of its own, the way map and filter do. The two side by
side:
Reorder the list itself: sort
Does: Puts the items of the list in the box in a new order
Never: Never keeps the order the list had before
A new list, in order: toSorted
Does: Makes a new list in order, in a box of its own
Never: Never changes tasks
sort reorders the list in its box; toSorted makes a new list
toSorted is the newer of the two, so most code you read will use
sort. Pick by one question: will anything need the old order
later? If not, sort is fine. If it will, or you are not sure,
use toSorted.
With no rule, sort reads everything as text
Now the surprise from the opening. Run it:
It prints 10, 15, 25, 30 and 5. With no rule, sort turns every
item into text and compares the texts one character at a time: the
first characters first, and the next ones only when those are the
same. Comparing "10" with "5", it looks at
"1" and "5", and "1" comes first, so 10 goes before 5.
Yesterday's list only looked right because every number in it had
two digits. Here is the same list read by you and by sort():
You, reading numbers
Does: Puts them in order by how big they are
sort() with no rule
Does: Puts them in order as text, character by character
The same five numbers, put in order by you and by sort()
Text has one more trap. Inside the computer every character has a
number, and text order follows those numbers: every digit comes
before every capital letter, and every capital before every
lower-case one. So a capital goes before any lower-case letter at
all:
Pay rent comes first, ahead of buy milk, only because its P
is a capital. Both traps have the same cure: tell sort what "in
order" means.
A rule that compares two items
The rules in lesson 4.3 took one item and gave back an answer about
it. One item is not enough to put things in order: whether 25 goes
before 10 depends on both of them. So the rule you give sort
takes two items:
It is the arrow function you already know, with two names on the
left instead of one, separated by a comma. sort hands the rule
two items at a time, a and b, and the rule answers with a
number. The short names are a habit in compare functions: a and
b only ever mean "one item" and "the other". TypeScript gives
both the type of the list's items, so for a list of numbers they
are number.
What sort reads from the answer is only its sign: whether it
is below zero, above zero or zero:
Below 0: a goes before b.
Above 0: b goes before a.
0: the two are equal, so they stay as they are.
a - b gives exactly that for numbers. When a is the smaller
one, a - b is below zero and a goes first, so the list comes
out from smallest to largest. A rule like this is called a
compare function, the name MDN (the Mozilla Developer Network,
the JavaScript reference from lesson 1.6) gives it.
Which two items sort asks about, and how many times, is up to
sort, not to you. Here are the three questions Node asks to sort
[10, 5, 25]: a solid arrow is a question from sort to your
rule, a dashed one is the rule's answer, and a box is what sort
does with it. Press Next step to follow them, or let it play:
sort
(a,b)=>a-b
1
sort to (a, b) => a - b: a=5,b=10
All 9 steps shown.Step 1 of 9: sort → (a, b) => a - b — a = 5, b = 10Step 2 of 9: (a, b) => a - b → sort — -5Step 3 of 9: sort — 5 before 10Step 4 of 9: sort → (a, b) => a - b — a = 25, b = 5Step 5 of 9: (a, b) => a - b → sort — 20Step 6 of 9: sort — 25 after 5Step 7 of 9: sort → (a, b) => a - b — a = 25, b = 10Step 8 of 9: (a, b) => a - b → sort — 15Step 9 of 9: sort — 25 after 10: [5, 10, 25]
All 9 steps shown.
Every question is about one pair, and the rule never sees the whole
list. That is why one short line is enough to put a list of any
length in order. Now watch it happen. Press Step, and the
player stops on the rule's line each time sort asks, with that
question's a and b in the variables:
The rule is on a line of its own only so that the player stops on
it for every question. The player runs in your browser, not in
Node, and a browser may ask fewer or other questions. Chrome and
Safari ask only two: about 5 and 10, then about 25 and 10. Once a
browser knows that 25 comes after 10, and 10 after 5, it never
needs to ask about 25 and 5. The list comes out the same.
For the largest first, swap the two: (a, b) => b - a. Every
answer changes sign, so every decision flips, and the list comes
out from largest to smallest.
Bad — no rule, so the minutes are
sorted as text, and 100 lands before 25.
Good — a compare function, so they
are sorted as numbers.
The first prints 10, 100, 25 and 5, and neither TypeScript nor Node
says a word, because sorting numbers as text is allowed. Whenever
you sort a list of numbers, give sort a compare function.
Words in dictionary order: localeCompare
For words, a - b is no use: TypeScript refuses to subtract one
string from another. Strings carry a method made for exactly this
job instead:
a.localeCompare(b) compares two words the way a dictionary does,
and answers in the language sort reads: below zero when a comes
first, above zero when b does, and 0 for the same word. A capital
no longer jumps the queue: Pay rent goes after call mom,
because p comes after c. A locale is a language together
with its rules for ordering letters; Node uses the one your
computer is set to, and for plain English words like these the
order comes out as above.
TaskKit prints its list from A to Z
Now TaskKit's step. It prints your tasks in the order you typed
them, which gets hard to scan once the list grows. From A to Z is
easier, and the order they were added should stay in tasks,
where add put it: a job for toSorted with localeCompare.
Open index.ts in ~/projects/taskkit. At the very end of the
file, replace the loop that prints the list:
TaskKit gives every task a capital first letter, but the rest of
the task stays as you typed it, so the capitals trap can still
strike in the middle of a task. Check the file with tsc (the
TypeScript compiler, which npx starts) and run it with two calls,
one typed with a capital M:
npx tsc prints nothing: the file passes. Then TaskKit prints:
Call dad comes before Call Mom, as in a dictionary. With a bare
tasks.toSorted(), the capital M would put Call Mom ahead of
Call dad.
Predict before you run
Read the three numbers as sort with no rule reads them, and
decide what it prints.
Predict
What does this program print?
The common mistake: a yes-or-no rule
Every rule you wrote in lesson 4.3 answered true or false. So
when you want the largest first, "is a bigger than b?" feels
like the right question to hand sort.
Common mistake
Giving sort a rule that answers true or false
You want the longest task first, and you write the question you
would ask yourself:
npx tsc --noEmit--types node longest.ts refuses the rule:
Type 'boolean' is not assignable to type 'number'.
The fix
Answer with a number, and let its sign decide. For the largest
first, that is b - a:
The first line of the error is one long line in your terminal,
broken here to fit the page. TS2345 is the error's code; TS is
for TypeScript. (a: number, b: number) => boolean is how
TypeScript writes "a rule that takes two numbers and gives back a
boolean"; Module 5 says more.
Read the error with the words from lesson 1.6: the argument, your
rule, gives back a boolean, and the parameter, the slot sort takes
its rule in, wants a rule that gives back a number.
Run the broken file with Node anyway and it prints
[ 25, 5, 100, 10 ], not sorted at all, with no error. sort turns
true into 1 and false into 0, so the rule never once answers
below zero, and the list comes out wrong. TypeScript catches it
before you run it.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
Which rule puts buy milk before Pay rent?
Check yourself
A compare function answers -3 for a and b. Which goes first?
Check yourself
You need A to Z and the order tasks were added. Which?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Sorting and its pitfalls
What things are
Word
What it means
Compare function
A rule with two names that answers with a number
a and b
The two items sort asks about, one pair at a time
Text order
Character by character: digits, capitals, lower case
Locale
A language and its rules for ordering letters
Code
Write
To
.sort()
Sort as text, changing the list itself
.sort((a, b) => a - b)
Sort numbers, smallest first
.sort((a, b) => b - a)
Sort numbers, largest first
a.localeCompare(b)
Compare two words as a dictionary does
.toSorted(…)
Get a new list in order; the old one stays
Rules
Rule
What it means
Below 0
a goes first
Above 0
b goes first
0
The two stay as they are
Numbers need a rule
With none, 10 comes before 5
sort changes the list
Even in a const box; toSorted never does
A number, not a yes
A rule giving true or false is TS2345
Where to go next
You can now sort numbers with (a, b) => a - b or b - a, sort
words as a dictionary does with localeCompare, and choose between
sort, which changes the list, and toSorted, which leaves it
alone. TaskKit prints its list from A to Z and keeps the order its
tasks were added.
Next is reduce. Every method so far has given back a list,
one item or a yes-or-no answer. reduce walks the whole list and
folds it into one value of your choosing, such as the total
minutes your day's tasks will take.
Before you move on, change TaskKit's rule to
(a, b) => b.localeCompare(a), predict the order
node index.ts add "call Mom" "buy milk" "call dad" prints, then
run it and compare (the heading still says A to Z: only the rule
changed). Put a.localeCompare(b) back afterwards.
2
(a, b) => a - b to sort: -5
3
sort, to itself: 5before10
4
sort to (a, b) => a - b: a=25,b=5
5
(a, b) => a - b to sort: 20
6
sort, to itself: 25after5
7
sort to (a, b) => a - b: a=25,b=10
8
(a, b) => a - b to sort: 15
9
sort, to itself: 25after10:[5,10,25]
[10, 5, 25].sort((a, b) => a - b): sort asks, the rule answers
Exercise · Read the code
Read what toSorted leaves behind
What is in minutes after these two lines run?
510152530
Smallest
101525305
As text: '5' after '3'
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkAdded: Call dadTasks added: 4 of 5, room for 1 moreList 80% fullYour list, A to Z:1. Buy milk2. Call dad3. Call Mom4. Pay rent
Outputtext
longest.ts:2:14 - 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'.2 minutes.sort((a, b) => a > b); ~~~~~~~~~~~~~~~Found 1 error in longest.ts:2
const minutes = [25, 5, 100, 10];minutes.sort((a, b) => a > b);console.log(minutes);
longest.tsts
const minutes = [25, 5, 100, 10];minutes.sort((a, b) => b - a);console.log(minutes);
Exercise · Fix the error
Sort the minutes as numbers
This program should print 5, the shortest task, but it prints
120. Fix it so minutes is sorted from smallest to largest.
Loading the editor…
Exercise · Fix the error
Answer with a number
TypeScript refuses this rule. Fix it so the longest task comes
first and the program prints 90.
Loading the editor…
Exercise · Write the code
Sort a copy, keep the list
Make byName: the tasks from A to Z, with a capital sorted among
the lower-case letters, not ahead of them, and without changing
tasks. Then
print the first task of byName and the first task of tasks. The
program prints buy milk, then pay rent.
Loading the editor…
ts
const minutes = [25, 5, 10];const fastest = minutes.toSorted((a, b) => a - b);