Sorting JavaScript Arrays: sort, Comparators, localeCompare, Stable Sort, reverse and toSorted
Why [10, 9, 1].sort() gives [1, 10, 9], how comparator functions work, sorting numbers, strings (localeCompare, Intl.Collator, natural "file2 before file10" order), dates and objects by several keys, stable sorting, broken comparators, reverse, toSorted, and shuffling correctly.
kvi5hnuCode Sprout team member6 min readOn this page
Sorting is one of the most common array operations and one of the most commonly gotten wrong. The default behavior surprises nearly everyone at first, so we start there.
The default sort compares strings
Without arguments, sort() converts every element to a string and orders them by UTF-16 code units, roughly "dictionary order for ASCII":
console.log([10, 9, 1, 100, 25].sort());
console.log([-1, -10, 5].sort());
console.log(["pear", "Apple", "banana", "apple"].sort());
console.log([true, false, true].sort());
[ 1, 10, 100, 25, 9 ]
[ -1, -10, 5 ]
[ 'Apple', 'apple', 'banana', 'pear' ]
[ false, true, true ]
"100" comes before "25" because the character "1" comes before "2", just as "apple" comes before "banana". Uppercase letters all come before lowercase ones ("Z" < "a"), and accented letters come after z. The default is only right for plain ASCII strings where case doesn't matter, so almost every sort needs a comparator.
sort also mutates the array and returns the same array, not a copy.
Comparator functions
Pass a function compare(a, b) that tells sort how two elements relate. Only the sign of the result matters:

const sizes = [10, 9, 1, 100, 25];
console.log(sizes.toSorted((a, b) => a - b)); // ascending
console.log(sizes.toSorted((a, b) => b - a)); // descending
[ 1, 9, 10, 25, 100 ]
[ 100, 25, 10, 9, 1 ]
a - b is negative when a is smaller, so smaller numbers come first. Swap to b - a for descending order. (toSorted, from article 60, returns a sorted copy; everything here works the same with sort.)
The subtraction trick only works for numbers (and dates, which convert to timestamps). For anything else, return -1, 1 or 0 explicitly:
const compareBy = (key) => (a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0);
const files = [{ name: "notes" }, { name: "budget" }, { name: "plan" }];
console.log(files.toSorted(compareBy("name")).map((f) => f.name));
const versions = [5n, 1n, 3n]; // BigInt can't be mixed with numbers
console.log(versions.toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0)));
[ 'budget', 'notes', 'plan' ]
[ 1n, 3n, 5n ]
Broken comparators
A comparator must be consistent: return a negative, zero or positive number, give the same answer for the same pair, and not contradict itself. A common mistake is returning a boolean:
[3, 1, 2].sort((a, b) => a > b); // WRONG: true/false become 1/0, never negative
false converts to 0 ("equal"), so the engine never learns that one element should come first. Depending on the engine and array size, the result may be unsorted. Similarly, Math.random() - 0.5 is not a valid way to shuffle (see below), and NaN values make subtraction comparators return NaN, which also gives unpredictable order. When the result is inconsistent, the specification only guarantees that you get some permutation of the elements.
Sorting strings properly
For text that people read, use localeCompare, which follows the language's real alphabetical rules (part 11 covers Intl in depth):
const words = ["pear", "Apple", "banana", "apple", "éclair"];
console.log(words.toSorted()); // code units
console.log(words.toSorted((a, b) => a.localeCompare(b, "en"))); // dictionary order
[ 'Apple', 'apple', 'banana', 'pear', 'éclair' ]
[ 'apple', 'Apple', 'banana', 'éclair', 'pear' ]
Natural (numeric) order
File names and version numbers contain numbers that should compare as numbers: "file2" before "file10". The numeric option does that:
const names = ["file10", "file2", "file1"];
console.log(names.toSorted());
console.log(names.toSorted((a, b) => a.localeCompare(b, "en", { numeric: true })));
const collator = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
console.log(["v10", "V9", "v1"].toSorted(collator.compare));
[ 'file1', 'file10', 'file2' ]
[ 'file1', 'file2', 'file10' ]
[ 'v1', 'V9', 'v10' ]
Intl.Collator creates the comparison rules once, so collator.compare is faster than calling localeCompare with options for every pair in a large array. sensitivity: "base" also treats "a", "A" and "á" as equal.
Sorting objects by several keys
Sort by the main key, and when it's equal (the comparator returns 0), fall back to the next key with ||:
const staff = [
{ name: "Cy", age: 30 },
{ name: "Ana", age: 25 },
{ name: "Bo", age: 30 },
{ name: "Di", age: 25 },
];
const byAgeThenName = (a, b) => a.age - b.age || a.name.localeCompare(b.name, "en");
console.log(staff.toSorted(byAgeThenName).map((p) => `${p.name} ${p.age}`));
const oldestFirst = (a, b) => b.age - a.age || a.name.localeCompare(b.name, "en");
console.log(staff.toSorted(oldestFirst).map((p) => p.name));
[ 'Ana 25', 'Di 25', 'Bo 30', 'Cy 30' ]
[ 'Bo', 'Cy', 'Ana', 'Di' ]
|| works because 0 is falsy: when the ages differ, the age result is used; when they're equal, the name comparison decides.
For a custom order that isn't alphabetical, map values to ranks:
const rank = { high: 0, medium: 1, low: 2 };
console.log(["low", "high", "medium", "high"].toSorted((a, b) => rank[a] - rank[b]));
[ 'high', 'high', 'medium', 'low' ]
Dates
Date objects subtract as millisecond timestamps, so a - b works:
const events = [new Date("2024-03-01"), new Date("2023-12-25"), new Date("2024-01-15")];
console.log(events.toSorted((a, b) => a - b).map((d) => d.toISOString().slice(0, 10)));
[ '2023-12-25', '2024-01-15', '2024-03-01' ]
ISO date strings like "2024-03-01" also sort correctly as plain strings, which is one reason that format is popular.
Sort is stable
Since ES2019, sort is guaranteed to be stable: elements the comparator considers equal keep their original relative order. In the age sort above, Ana stayed before Di and Cy before Bo, because that's how they appeared in the input. Stability means you can sort in several passes, with the least important key first:
const staff = [
{ name: "Cy", age: 30 },
{ name: "Ana", age: 25 },
{ name: "Bo", age: 30 },
];
const byName = staff.toSorted((a, b) => a.name.localeCompare(b.name, "en"));
const byAge = byName.toSorted((a, b) => a.age - b.age); // equal ages stay in name order
console.log(byAge.map((p) => p.name));
[ 'Ana', 'Bo', 'Cy' ]
This is how clicking several column headers in a table works.
undefined and holes
sort always moves undefined values to the end, followed by holes, without calling the comparator for them:
console.log([3, undefined, 1, , 2].sort((a, b) => a - b));
[ 1, 2, 3, undefined, <1 empty item> ]
null gets no special treatment: it's passed to your comparator (and converts to 0 in subtraction).
reverse and toReversed
reverse() reverses the array in place and returns it; toReversed() returns a reversed copy:
const steps = ["one", "two", "three"];
console.log(steps.toReversed(), steps);
steps.reverse();
console.log(steps);
[ 'three', 'two', 'one' ] [ 'one', 'two', 'three' ]
[ 'three', 'two', 'one' ]
To sort descending, prefer a descending comparator over sort().reverse(): it's one pass and stays stable.
Shuffling correctly
arr.sort(() => Math.random() - 0.5) is a popular one-liner and a bad shuffle: the comparator is inconsistent, so some orders are much more likely than others, depending on the engine's algorithm. Use the Fisher–Yates shuffle, which gives every order equal probability in O(n):
function shuffle(items) {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1)); // 0 <= j <= i
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
For anything security-related (lotteries, tokens), use crypto.getRandomValues instead of Math.random.
Performance
sort runs in O(n log n) time; V8 uses an algorithm called TimSort, which is especially fast on data that's already partly sorted. The comparator is called many times (roughly n log n), so keep it cheap: precompute expensive keys first.
const titles = ["The Zoo", "an apple", "A Bridge"];
const normalize = (t) => t.toLowerCase().replace(/^(the|an|a) /, "");
const sorted = titles
.map((title) => ({ title, key: normalize(title) }))
.sort((a, b) => a.key.localeCompare(b.key, "en"))
.map((entry) => entry.title);
console.log(sorted);
[ 'an apple', 'A Bridge', 'The Zoo' ]
Common questions
Why does sort convert numbers to strings?
History: the original sort had to work for any mix of values, and strings were the one comparison every value supports. Changing it now would break existing websites, so the default stays and comparators are the fix.
Does sort return a new array?
No. It sorts in place and returns the same array. const sorted = arr.sort() sorts arr too. Use toSorted (or [...arr].sort()) to keep the original.
How do I sort an object's keys or a Map?
Sort its entries (code below), or use new Map([...map].sort(...)).
Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b, "en")))
How do I sort case-insensitively?
a.localeCompare(b, "en", { sensitivity: "base" })
Or compare a.toLowerCase() and b.toLowerCase() for plain ASCII.
Summary
- Without a comparator,
sortcompares elements as strings:[10, 9, 1].sort()is[1, 10, 9]. - A comparator returns a negative number (a first), positive (b first) or 0 (keep order);
a - bsorts numbers ascending,b - adescending. - Comparators must return consistent numbers; returning booleans or random values gives unreliable results.
- Use
localeCompareorIntl.Collatorfor human text, with{ numeric: true }for natural order. - Combine keys with
||; sort is stable, so equal elements keep their order. sortandreversemutate;toSortedandtoReversedreturn copies.- Shuffle with Fisher–Yates, not
sort(() => Math.random() - 0.5).
Practice Questions
What does ["b", "a", "C"].sort() return, and why?
Answer
[ 'C', 'a', 'b' ]. Default sorting compares UTF-16 code units, and every uppercase letter comes before every lowercase letter.
Sort this array by p descending, then n ascending:
[{ n: "x", p: 3 }, { n: "y", p: 1 }, { n: "z", p: 3 }]
Answer
items.toSorted((a, b) => b.p - a.p || a.n.localeCompare(b.n, "en"))
Gives x, z, y.
What's wrong with this code in a function that receives scores from its caller?
const top3 = scores.sort((a, b) => b - a).slice(0, 3);
Answer
sort reorders the caller's array as a side effect. Use scores.toSorted((a, b) => b - a).slice(0, 3).
Sort ["item20", "item3", "Item100"] naturally and ignoring case.
Answer
list.toSorted((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }))
Gives [ 'item3', 'item20', 'Item100' ].
Next: JavaScript join, Array.isArray, Array-Like Objects and Strings as Arrays

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.