Custom Sorts - Arrays
sort() with no arguments converts every item to a string and orders the strings by their UTF-16 code units. That suits simple lower-case text and little else. Passing a compare function tells sort() how to order any two items, which makes it work for numbers, objects and text in any language.
The problem with numbers
Section titled “The problem with numbers”Because the default sort compares strings, '100' comes before '9' for the same reason that “apple” comes before “banana”:
const prices = [25, 100, 9, 1000, 42];
console.log(prices.sort());This prints:
[ 100, 1000, 25, 42, 9 ]Writing a compare function
Section titled “Writing a compare function”sort() calls the compare function with two items, a and b, and reads the sign of what it returns:
- a negative number puts
abeforeb - a positive number puts
bbeforea - zero leaves the two in their current order
const prices = [25, 100, 9, 1000, 42];
prices.sort((a, b) => { if (a < b) return -1; if (a > b) return 1; return 0;});console.log(prices);This prints:
[ 9, 25, 42, 100, 1000 ]For numbers, subtracting one from the other gives a value with the right sign, so the whole function shortens to a - b. Swapping the operands to b - a sorts from largest to smallest:
const ascending = [25, 100, 9, 1000, 42].sort((a, b) => a - b);const descending = [25, 100, 9, 1000, 42].sort((a, b) => b - a);
console.log(ascending);console.log(descending);This prints:
[ 9, 25, 42, 100, 1000 ][ 1000, 100, 42, 25, 9 ]The engine chooses which pairs to compare and in what order, and that differs between browsers, so the compare function should only compare and should not rely on being called in any particular sequence.
Sorting objects by a property
Section titled “Sorting objects by a property”An array of objects sorts on whichever property the compare function reads. For numbers, subtract. For text, localeCompare() returns a negative number, zero or a positive number, which is exactly what sort() expects:
const books = [ { title: 'Emma', author: 'Austen', year: 1815 }, { title: 'Dune', author: 'Herbert', year: 1965 }, { title: 'Persuasion', author: 'Austen', year: 1817 }, { title: 'Beloved', author: 'Morrison', year: 1987 },];
const byYear = books.toSorted((a, b) => a.year - b.year);console.log(byYear.map((book) => `${book.year} ${book.title}`));
const byTitle = books.toSorted((a, b) => a.title.localeCompare(b.title));console.log(byTitle.map((book) => book.title));This prints:
[ '1815 Emma', '1817 Persuasion', '1965 Dune', '1987 Beloved' ][ 'Beloved', 'Dune', 'Emma', 'Persuasion' ]To sort on a second property when the first is equal, join the two comparisons with ||. A first comparison of zero is falsy, so the second one decides. This sorts by author, and then by year with the newest first:
const books = [ { title: 'Emma', author: 'Austen', year: 1815 }, { title: 'Dune', author: 'Herbert', year: 1965 }, { title: 'Persuasion', author: 'Austen', year: 1817 }, { title: 'Beloved', author: 'Morrison', year: 1987 },];
const sorted = books.toSorted( (a, b) => a.author.localeCompare(b.author) || b.year - a.year,);console.log(sorted.map((book) => `${book.author}, ${book.title}`));This prints:
[ 'Austen, Persuasion', 'Austen, Emma', 'Herbert, Dune', 'Morrison, Beloved']Custom Object Sorts goes further with sorting records.
Sorting text properly
Section titled “Sorting text properly”The default sort puts capitals before lower-case letters and accented letters after z. localeCompare() follows the rules of a language instead:
const names = ['émile', 'Zoe', 'adam', 'Ömer'];
console.log(names.toSorted());console.log(names.toSorted((a, b) => a.localeCompare(b, 'en')));This prints:
[ 'Zoe', 'adam', 'Ömer', 'émile' ][ 'adam', 'émile', 'Ömer', 'Zoe' ]For sorting a large list of strings, an Intl.Collator created once and passed as collator.compare is faster than calling localeCompare() for every pair.
sort changes the array
Section titled “sort changes the array”sort() sorts the array in place and returns the same array, so a variable holding its result is not a copy. toSorted(), added in ES2023, takes the same compare function and returns a new array:
const prices = [25, 100, 9];
const sorted = prices.sort((a, b) => a - b);console.log(sorted === prices, prices);
const original = [25, 100, 9];const copy = original.toSorted((a, b) => a - b);console.log(copy, original);This prints:
true [ 9, 25, 100 ][ 9, 25, 100 ] [ 25, 100, 9 ]Since ES2019, both sorts are stable, which means items that compare as equal keep their original order. That is what makes sorting by one property and then by another reliable.
Steve Griffith covers this topic in his video Custom Array Sorts in JavaScript.