sort
sort puts an array in order, and its default behaviour surprises nearly everyone because it sorts by text.
sort changes the array in place and sorts as text by default, so 10 lands before 9. A compare function fixes that: return a negative number, zero or a positive number to say which item comes first.
EXERCISE
1The Default Sort Is Alphabetical
Calling sort with no arguments converts every item to text before comparing, which is right for words and wrong for numbers.
On words, the default is what you want:
const names = ["Grace", "Ada", "Alan"];
names.sort();
console.log(names); // [ 'Ada', 'Alan', 'Grace' ]
On numbers, it is not:
const numbers = [10, 9, 100, 1];
numbers.sort();
console.log(numbers); // [ 1, 10, 100, 9 ]
// Every item was turned into text first:
// "1", "10", "100", "9"
// and "9" comes after "1" in text order, just as "z" comes after "a".
Two more things the default does:
// It changes the original array, it does not return a copy:
const original = [3, 1, 2];
const returned = original.sort();
console.log(original); // [ 1, 2, 3 ] <- changed
console.log(returned === original); // true <- same array
// To keep the original, copy it first:
const safe = [...original].sort();
Uppercase before lowercase, as in the strings unit:
const names = ["ada", "Grace", "alan"];
names.sort();
console.log(names); // [ 'Grace', 'ada', 'alan' ]
// Sort case-insensitively with a compare function:
names.sort((a, b) => a.localeCompare(b));
console.log(names); // [ 'ada', 'alan', 'Grace' ]
Pro Tip:
sort()with no argument is only correct for a list of similarly-cased words. For numbers, for mixed case and for objects it gives a confidently wrong answer with no error, which makes it one of the easiest bugs in JavaScript to ship. Assume you need a compare function unless you have checked otherwise.
EXERCISE
2The Compare Function
Passing a function of two arguments tells sort how to order any pair, and the rule for what to return is short.
The contract:
// sort hands your function two items, a and b, and expects:
// a negative number -> a comes first
// zero -> leave their order alone
// a positive number -> b comes first
For numbers, subtraction does exactly that:
const numbers = [10, 9, 100, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // [ 1, 9, 10, 100 ] ascending
numbers.sort((a, b) => b - a);
console.log(numbers); // [ 100, 10, 9, 1 ] descending
a - b is negative when a is smaller, which puts the smaller one first. That is the whole trick.
Sorting objects by a field:
const users = [
{ name: "Grace", age: 45 },
{ name: "Ada", age: 36 },
{ name: "Alan", age: 41 },
];
users.sort((a, b) => a.age - b.age);
console.log(users.map((u) => u.name)); // [ 'Ada', 'Alan', 'Grace' ]
Sorting objects by a text field:
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users.map((u) => u.name)); // [ 'Ada', 'Alan', 'Grace' ]
// localeCompare already returns a negative number, zero or a positive
// one, which is exactly the contract sort is asking for.
Sorting by two fields, with a tie-break:
const items = [
{ name: "Tea", price: 40 },
{ name: "Cocoa", price: 40 },
{ name: "Coffee", price: 120 },
];
items.sort((a, b) => a.price - b.price || a.name.localeCompare(b.name));
console.log(items.map((i) => i.name)); // [ 'Cocoa', 'Tea', 'Coffee' ]
// When prices tie, a.price - b.price is 0, which is falsy,
// so || moves on to the name comparison.
(a, b) => a - b for numbers and (a, b) => a.name.localeCompare(b.name) for text will cover almost everything you sort. Memorise those two lines rather than the negative-zero-positive rule, and the rule will make sense the first time you need something more unusual.
EXERCISE
3Sorting Without Destroying the Original
sort changes the array it is called on, which is a problem whenever something else is still using that array.
The problem:
const scores = [30, 10, 20];
function highest(list) {
return list.sort((a, b) => b - a)[0];
}
console.log(highest(scores)); // 30
console.log(scores); // [ 30, 20, 10 ] <- caller's array reordered
The function answered correctly and quietly rearranged data that belonged to someone else.
Copy first:
function highest(list) {
return [...list].sort((a, b) => b - a)[0];
}
const scores = [30, 10, 20];
console.log(highest(scores)); // 30
console.log(scores); // [ 30, 10, 20 ] <- intact
toSorted does the copy for you:
const scores = [30, 10, 20];
const ranked = scores.toSorted((a, b) => b - a);
console.log(ranked); // [ 30, 20, 10 ]
console.log(scores); // [ 30, 10, 20 ] <- untouched
// toSorted, toReversed and toSpliced are the newer copying versions
// of sort, reverse and splice. Support is good in modern browsers
// and Node, so prefer them when you can.
reverse has the same problem:
const letters = ["a", "b", "c"];
letters.reverse();
console.log(letters); // [ 'c', 'b', 'a' ] <- changed in place
const back = [..."abc"].toReversed();
console.log(back); // [ 'c', 'b', 'a' ]
Pro Tip: A function that sorts an array it was handed is changing data its caller can still see, and that is the kind of bug that shows up far away from its cause. Copy before you sort, either with
[...list].sort(...)or withtoSorted(...), unless you deliberately mean to reorder the original.
