Arrays
sort() and toSorted()
Sorting with a compare function; without one, items are compared as strings.
Why it exists
Almost every list is shown in some order: products by price, emails by date, players by score, contacts by name. Writing a sort by hand is slow and error-prone, so it's built into arrays. All you do is explain how to compare two items — sort handles the rest.
Where it's used
- Catalogues: "cheapest first", "by rating", "newest".
- Tables sorted by clicking a column header.
- Leaderboards and "top N".
- Alphabetical lists:
names.sort((a, b) => a.localeCompare(b)).
Syntax
array.sort((a, b) => a - b) // changes the array
array.toSorted((a, b) => a - b) // a new arrayExamples
[300, 9, 25].toSorted((a, b) => a - b); // → [9, 25, 300][10, 9, 100].sort(); // → [10, 100, 9]
[10, 9, 100].sort((a, b) => a - b); // → [9, 10, 100]const products = [{ name: "Tea", price: 200 }, { name: "Juice", price: 90 }];
products.toSorted((a, b) => a.price - b.price)[0].name; // → "Juice"["pear", "Apple", "banana"].sort((a, b) => a.localeCompare(b)); // → ["Apple", "banana", "pear"]localeCompareResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
sort calls the compare function many times on pairs of items and uses the answer to decide which goes first:
- a result below zero —
agoes beforeb; - above zero —
bgoes beforea; - zero — their order stays as it is.
For numbers this is short: a - b sorts ascending, b - a descending. For objects, compare a field: a.price - b.price. For strings, a.localeCompare(b), which respects the language's alphabet.
Without a compare function, sort turns items into strings and compares them character by character: [10, 9, 100].sort() gives [10, 100, 9].
The sort is stable: equal items keep their original order.
sort rearranges items in the same array and returns it. toSorted (2023) does the same on a copy.
Traps
How it differs from…
- Changing arrays and copies
sortis one of the methods that change an array in place. Which others do, and how to avoid it, is in a separate entry.array.reduce()If you only need the largest or smallest item, there's no need to sort the whole array — one pass of reduce or a loop is enough.
When to pick something else
Don't sort for a single item (a maximum or minimum) — that's wasted work. And don't re-sort a big list that hasn't changed on every render: keep the result.
Practice
Lessons where this appears
- The conveyor at the fish factoryTale · Chapter 10 · map, filter, reduce
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- A shift on the conveyorWorkshop · Chapter 10 · map, filter, reduce
- The jammed conveyorBoss · Chapter 10 · map, filter, reduce
- The case of the eternal 1.9.0Investigation · Chapter 25 · npm and packages
- Five ticketsWorkshop · Chapter 26 · Debugging