Lesson 2 · Unit 04
Sort by a key
Key functions, comparators, descending order and tie-breakers
What you practise
- Key functions and comparators, descending order, tie-breakers
Try a question from this lesson
Pick one
You want a list of words ordered from shortest to longest. What should the sort compare?
Correct answer
The length of each word
Why
You sort the words, but you compare a property of each word: its length. That property is called the key. Comparing the words themselves gives alphabetical order.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Key functions
A key function takes one item and returns the value to sort by.
Python's sort accepts it directly as key=. JavaScript and TypeScript say the same thing with a comparator that compares the keys of its two items.
Either way the items themselves are moved; the keys only decide the order.
words = ["banana", "fig", "pear"]
words.sort(key=len)
print(*words)const words = ["banana", "fig", "pear"];
words.sort((a, b) => a.length - b.length);
console.log(words.join(" "));const words = ["banana", "fig", "pear"];
words.sort((a, b) => a.length - b.length);
console.log(words.join(" "));Python notekey=len passes the function itself, without parentheses. The sort calls it once for every item.
TypeScript notea and b are inferred as string because words is a string[], so .length type-checks with no annotations.
Concept
Tie-breakers
When two items have the same key, a second key can break the tie.
In Python the key can be a tuple: tuples are compared by their first parts, and by their second parts only when the first are equal.
In JavaScript and TypeScript, chain two comparisons with ||: when the first difference is 0, the second comparison decides.
words = ["pear", "fig", "kiwi", "date"]
words.sort(key=lambda w: (len(w), w))
print(*words)const words = [
"pear", "fig", "kiwi", "date",
];
words.sort(
(a, b) =>
a.length - b.length ||
a.localeCompare(b),
);
console.log(words.join(" "));const words = [
"pear", "fig", "kiwi", "date",
];
words.sort(
(a, b) =>
a.length - b.length ||
a.localeCompare(b),
);
console.log(words.join(" "));Python note(3, "fig") < (4, "date") because 3 < 4. (4, "date") < (4, "kiwi") because the first parts tie and "date" < "kiwi".
JavaScript notex || y gives y only when x is 0, so the alphabetical comparison runs only on a length tie.
TypeScript notea.localeCompare(b) returns a number: negative, zero or positive. That is exactly what a comparator must return.
9 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 1× type the answer
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.