Sorting arrays with a comparator
sort changes the array it is called on and returns the same array, and without a comparator it puts the items in the order of their text. That default is the reason a list of numbers comes out as 1, 10, 100, 25, 9: every item was turned into a string and compared character by character. A JavaScript program that sorts numbers needs a comparator, and a program that sorts text often needs one too.
This lesson shows what the default does, how a comparator answers with a negative number, zero or a positive one, the stable sort that keeps equal items in their order, and toSorted, which returns a new array instead of changing the old one. The copying methods of the next lesson build on the same idea.
The default is string order
With no argument, sort converts the items to strings and compares them by their UTF-16 code units. Two-digit numbers sort before one-digit numbers that start with a larger digit, and capitals come before lower-case letters. The program sorts the same array and prints it before and after.
const numbers = [10, 9, 1, 100, 25];
console.log('as they are:', numbers.join(','));
console.log('sort with no comparator:', numbers.sort().join(','));
console.log('the array itself was sorted:', numbers.join(','));
console.log('words sort as expected:', ['pear', 'apple', 'fig'].sort().join(','));
console.log('and capitals come first:', ['B', 'a', 'C'].sort().join(','));
node defaultorder.js
as they are: 10,9,1,100,25
sort with no comparator: 1,10,100,25,9
the array itself was sorted: 1,10,100,25,9
words sort as expected: apple,fig,pear
and capitals come first: B,C,a
The numbers are in text order, so 10 comes before 9 and 100 before 25. The second and the third line are the same because sort works in place: there is no printed result to look at unless the array is printed after the call. Words are in the order a dictionary uses, until capitals enter: B and C have smaller codes than a, so they come first.
A comparator returns a number
The comparator is a function of two items that answers with a number: negative when the first belongs before the second, positive when it belongs after, and zero when the order does not matter. Subtracting the two numbers gives all three answers at once, which is why (a, b) => a - b is the shortest correct comparator for numbers. A comparator that returns true or false answers only two of the three questions.
const numbers = [10, 9, 1, 100, 25];
const ascending = (a, b) => a - b;
const descending = (a, b) => b - a;
console.log('ascending:', numbers.slice().sort(ascending).join(','));
console.log('descending:', numbers.slice().sort(descending).join(','));
console.log('the three answers:', ascending(1, 2), ascending(2, 2), ascending(2, 1));
const asBoolean = (a, b) => a > b;
console.log('a boolean gives two:', asBoolean(1, 2), asBoolean(2, 2), asBoolean(2, 1));
const words = ['ccc', 'a', 'bb'];
console.log('by length:', words.slice().sort((a, b) => a.length - b.length).join(','));
node comparator.js
ascending: 1,9,10,25,100
descending: 100,25,10,9,1
the three answers: -1 0 1
a boolean gives two: false false true
by length: a,bb,ccc
slice before the call keeps the original for the second sort, which is how one array can be sorted two ways in one program. The third line is the comparator answering all three cases, and the fourth is the boolean version answering false for both 1 < 2 and 2 === 2: the two are read as 0 and the pair looks equal to sort. The last line compares lengths, so the comparator can be any number a function can produce.
Stable sort and objects
Since 2019 every engine has a stable sort: items the comparator calls equal stay in the order they had. That makes a two-step sort possible, where the second call sorts by the more important key and keeps the order of the first. The program sorts records by one field and prints the names, so the stability is visible.
const people = [
{ name: 'ada', team: 'blue' },
{ name: 'alan', team: 'red' },
{ name: 'grace', team: 'blue' },
{ name: 'edsger', team: 'red' },
];
const byTeam = (a, b) => {
if (a.team < b.team) {
return -1;
}
if (a.team > b.team) {
return 1;
}
return 0;
};
const sorted = people.slice().sort(byTeam);
console.log('sorted:', sorted.map((person) => `${person.name}:${person.team}`).join(' '));
console.log('the original order:', people.map((person) => person.name).join(' '));
console.log('sort changes the array it is called on:', people.sort(byTeam) === people);
console.log('numbers taken as text again:', [2, 10, 1].sort().join(','));
node stability.js
sorted: ada:blue grace:blue alan:red edsger:red
the original order: ada alan grace edsger
sort changes the array it is called on: true
numbers taken as text again: 1,10,2
The two blue records stayed in their original order, and so did the two red ones, which is what stability means here. The third line says that sort returns the array it was called on and not a new one, so a function that is handed a list and sorts it changes the list of its caller. The last line is the same string-order trap in one line, and a reminder that the comparator is not optional for numbers.
toSorted leaves the original alone
toSorted takes the same comparator and returns a sorted copy, and the original keeps its order. It arrived with toReversed, toSpliced and with in the group of methods that do not change the array, and Node.js 20 is the oldest release that has all of them. Before that, the copy was made with the spread syntax.
const scores = [30, 10, 20];
const sorted = scores.toSorted((a, b) => a - b);
console.log('toSorted:', sorted.join(','));
console.log('the original:', scores.join(','));
console.log('another array:', sorted !== scores);
const words = ['b', 'a'];
const copy = [...words];
copy.sort();
console.log('spread and sort:', copy.join(','), 'the original:', words.join(','));
console.log('sort returns the same array:', words.sort() === words, words.join(','));
node tosorted.js
toSorted: 10,20,30
the original: 30,10,20
another array: true
spread and sort: a,b the original: b,a
sort returns the same array: true a,b
The first three lines are the whole argument for toSorted: a sorted array, an untouched original, and two different objects. The spread does the same job with one line more, and both are worth knowing, because the spread also works on the other methods and on older releases. The last line shows what the old method returns: the same array, now in the other order, which the final print confirms.
Exercises
- Sort [1, 5, 12, 3] without a comparator and then with one. Which position does 12 take in each result?
- Change asBoolean in comparator.js to (a, b) => a < b. Which of the three answers changes?
- Sort the people in stability.js by team and then by name inside each team with two calls. Which names swap places?
- Replace numbers.slice().sort(ascending) with numbers.toSorted(ascending). Which lines of the output change?
- Write a comparator that sorts words by their last letter, and say what it returns for two words that end with the same letter.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
[10, 9, 1].sort()give?Answer
[1, 10, 9]
With no comparator the items are compared as text, so 10 comes before 9.
-
What does a comparator have to return?
Answer
A negative number, zero or a positive number
The sign of the number is the three-way answer that sort needs, and a boolean gives only two of the three.
-
What does this program print?
console.log([3, 20, 100].sort((a, b) => a - b).join(","));Answer
3,20,100
The comparator subtracts, so the numbers are compared as numbers and not as text.
-
What does this program print?
const a = [3, 1, 2]; const b = a.sort(); console.log(a === b, b.join(","));Answer
true 1,2,3
sort returns the array it sorted, so the two names hold the same object.
-
What does
toSorteddo differently fromsort?Answer
It returns a new sorted array and leaves the original in its order
The to methods of the array do not change the receiver, which is what a pure function needs.
-
What does this program print?
const a = [2, 1]; const b = a.toSorted(); console.log(a.join(","), b.join(","));Answer
2,1 1,2
The original keeps its order and the copy is the sorted one.
-
Why do capitals come before lower-case letters in the default sort?
Answer
The comparison is by UTF-16 code unit, and capital letters have smaller codes
The codes of A to Z are below those of a to z, so a plain text comparison puts capitals first.
-
What is a stable sort?
Answer
One that keeps items the comparator calls equal in their original order
Stability is what makes a second sort by another key keep the order of the first.
-
What does this program print?
const people = [{ n: "a", t: 1 }, { n: "b", t: 1 }]; console.log(people.sort((x, y) => x.t - y.t).map((p) => p.n).join(""));Answer
ab
The comparator calls the two items equal, and a stable sort keeps their order.
-
Which comparator sorts records by age from the oldest to the youngest?
Answer
(a, b) => b.age - a.age
A positive answer puts the first item later, so subtracting the first age from the second gives the descending order.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev