.sort() and .reverse()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Putting a List in Order
Imagine you open your Codédex and want to display your caught Codémon in alphabetical order from A to Z so you can find them easily.
When an array contains strings, calling `.sort()` with no arguments automatically arranges them in alphabetical order:
const team = ["Zap", "Pyrochu", "Aquachu", "Florachu"];
team.sort();
console.log(team);sort modifies the original array
Unlike `.map()`, `.filter()`, or `.slice()`, `.sort()` directly reorders the array it is called on! If you want to keep the original order intact, make a copy first: `[...team].sort()`.
Exercise 2 — The Number Trap
Watch out when sorting numbers! By default, `.sort()` converts every item into text and compares them alphabetically character by character. Because the character `"1"` comes before `"9"`, JavaScript puts `10` and `100` before `9`:
const levels = [10, 9, 100, 25];
levels.sort();
console.log(levels);Notice the result: `[10, 100, 25, 9]`. Calling `.sort()` with no arguments works great for words, but never for numbers!
Exercise 3 — Ascending and Descending
To sort numbers by their actual numeric value, pass a comparison function to `.sort()`. It compares two numbers `a` and `b` at a time: - `(a, b) => a - b` sorts numbers from smallest to largest (ascending). - `(a, b) => b - a` sorts numbers from largest to smallest (descending).
const levels = [10, 9, 100, 25];
levels.sort((a, b) => a - b);
console.log("Ascending:", levels);
levels.sort((a, b) => b - a);
console.log("Descending:", levels);Exercise 4 — Quiz: Sorted How?
What does this code print?
const nums = [5, 40, 300];
nums.sort();
console.log(nums);300,40,55,40,300300,5,4040,5,300Hint : Without a comparison function, the values are compared as text.
Exercise 5 — Highest First
Sort the levels from largest to smallest.
Hint : A subtraction whose order decides the direction. Largest first means the second value leads.
Exercise 6 — Sorting Objects
With objects, the comparison function reads the property you want to order by. Everything else stays the same:
const team = [
{ name: "Zap", level: 4 },
{ name: "Metachu", level: 15 },
{ name: "Aquachu", level: 12 }
];
const byLevel = [...team].sort((a, b) => b.level - a.level);
byLevel.forEach(({ name, level }) => console.log(name + " Lv." + level));For text properties, subtraction makes no sense. Use `localeCompare`, which returns the negative or positive number `sort` expects:
const team = [
{ name: "Zap" },
{ name: "Aquachu" },
{ name: "Metachu" }
];
const byName = [...team].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((cdm) => cdm.name).join(", "));Exercise 7 — Quiz: Who's First?
What does this code print?
const team = [
{ name: "Zap", level: 4 },
{ name: "Metachu", level: 15 }
];
const sorted = [...team].sort((a, b) => b.level - a.level);
console.log(sorted[0].name);MetachuZap15undefinedHint : Work out which direction the comparison produces, then read the first element.
Exercise 8 — reverse Flips the Order
Another cool command is `reverse`, it turns the array around. Like `sort`, it modifies the original:
const team = ["Aquachu", "Pyrochu", "Zap"];
team.reverse();
console.log(team);Sorting then reversing gives the same result as sorting the other way, but it costs two passes. Prefer swapping the comparison:
const levels = [12, 4, 15];
console.log([...levels].sort((a, b) => a - b).reverse());
console.log([...levels].sort((a, b) => b - a));Exercise 9 — Alphabetical Roster
Sort a copy of the team alphabetically, leaving the original untouched.
Hint : One symbol protects the original, and text needs no comparison function.
Exercise 10 — sort Cheat Sheet
Match each line with its effect.
arr.sort()arr.sort((a,b) => a-b)arr.sort((a,b) => b-a)[...arr].sort()Exercise 11 — Tournament Ranking
Publish the tournament rankings from the fighters' scores, without ever modifying the original list.
Step 1: build `byScore`, a sorted copy from the highest score to the lowest, and print one line per fighter in the format `"N. name - X pts"`, numbered from 1. Step 2: print `"Winner: X"` with the name of the first one. Step 3: build `byName`, a copy sorted alphabetically, and print the names joined with `", "`. Step 4: print `"Original first: X"` with the first name of the untouched `fighters`.
Expected output:
1. Metachu - 95 pts
2. Aquachu - 60 pts
3. Zap - 45 pts
Winner: Metachu
Aquachu, Metachu, Zap
Original first: Zapconst fighters = [
{ name: "Zap", score: 45 },
{ name: "Metachu", score: 95 },
{ name: "Aquachu", score: 60 }
];
// Write your code here