JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5
To sort an array of numbers in JavaScript, pass a compare function: arr.sort((a, b) => a – b). Without it, sort() compares items as text, which is why 10 lands before 5. This guide shows the right way to sort numbers, objects, strings, dates and file names, with output we ran on Node 24.
- The default JavaScript sort array behaviour compares strings:
[10, 1, 5, 100, 25].sort()gave[1, 10, 100, 25, 5]. - Use
(a, b) => a - bfor ascending numbers andb - afor descending. sort()changes the original array;toSorted()returns a sorted copy and leaves it alone.- A compare function that returns
a > b(a boolean) is a real bug: it left[3, 1, 2, 5, 4]unsorted in our test.
Sorting looks like the simplest thing an array can do, yet JavaScript’s sort() surprises almost every developer once. Numbers come out in the wrong order, the original array changes behind your back, and names with capitals or accents land in odd places. This JavaScript sort array guide fixes all three. Every example below was run on Node.js v24.22.1, and the outputs are copied from that run. The behaviour is defined by the language standard, so modern browsers match it. If arrays are new to you, start with our JavaScript tutorial for beginners.
Quick answer
const nums = [10, 1, 5, 100, 25];
nums.sort((a, b) => a - b); // [1, 5, 10, 25, 100]
nums.sort((a, b) => b - a); // [100, 25, 10, 5, 1]
That one compare function fixes the most common sorting bug. The rest of this guide explains why it works and how to handle every other kind of data.
Why 10 comes before 5
console.log([10, 1, 5, 100, 25].sort());
[ 1, 10, 100, 25, 5 ]
Without a compare function, sort() converts every element to a string and compares them character by character. “10” starts with “1”, which comes before “5”, so 10 sorts before 5, just as “apple” comes before “banana”. This default made sense for the arrays of strings early JavaScript dealt with, and it cannot change without breaking old websites. The fix is to tell sort() how to compare.
How compare functions work
A compare function receives two items, a and b, and returns a number:
| Return value | Meaning |
|---|---|
| Negative | a comes before b |
| Positive | a comes after b |
| Zero | Keep their current relative order |
Subtraction gives exactly this for numbers: if a is smaller, a - b is negative and a goes first. Swap the operands for descending order. Any rule that returns a negative, positive or zero number works, which is how you sort objects, dates and custom orders.
sort() changes the original; toSorted() does not
const orig = [3, 1, 2];
const r = orig.sort();
console.log(orig, r === orig); // [ 1, 2, 3 ] true
const o2 = [3, 1, 2];
const s2 = o2.toSorted();
console.log(o2, s2); // [ 3, 1, 2 ] [ 1, 2, 3 ]
sort() sorts in place and returns the same array, so any other variable pointing to that array sees the change. This causes subtle bugs in React state and shared data. toSorted(), added in ES2023, returns a new sorted array and leaves the original untouched. It works in Node 20+ and current browsers. On older platforms, copy first with [...arr].sort(...); see our spread operator guide.
Sorting strings properly
console.log(["banana", "Cherry", "apple"].sort());
console.log(["banana", "Cherry", "apple"].sort((a, b) => a.localeCompare(b)));
console.log(["é", "e", "z", "a"].sort());
console.log(["é", "e", "z", "a"].sort((a, b) => a.localeCompare(b)));
[ 'Cherry', 'apple', 'banana' ]
[ 'apple', 'banana', 'Cherry' ]
[ 'a', 'e', 'z', 'é' ]
[ 'a', 'e', 'é', 'z' ]
The default sort uses UTF-16 code units, so every capital letter comes before every lowercase letter, and accented letters land after “z”. localeCompare() sorts the way people expect, ignoring case differences in order and placing “é” next to “e”. For large lists, create one Intl.Collator and reuse its compare method, which avoids repeated setup.
Natural sort for file names and versions
const files = ["file10", "file2", "file1"];
console.log(files.sort());
console.log(files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));
[ 'file1', 'file10', 'file2' ]
[ 'file1', 'file2', 'file10' ]
The numeric: true option compares digit runs as numbers, which gives “natural” order for file names, invoice IDs and simple version labels. It is one of the most useful and least known options in JavaScript.
Sorting an array of objects
const users = [
{ name: "Asha", age: 31, city: "Pune" },
{ name: "Ravi", age: 25, city: "Delhi" },
{ name: "Li", age: 31, city: "Delhi" },
{ name: "Sam", age: 25, city: "Pune" },
];
console.log(users.toSorted((a, b) => a.age - b.age).map(u => u.name));
[ 'Ravi', 'Sam', 'Asha', 'Li' ]
Pick the property inside the compare function. Numbers use subtraction; strings use localeCompare. Ravi and Sam are both 25 and kept their original order, which brings us to multi-field sorting and stability. For more on transforming results, see our JavaScript array methods guide.
Sort by several fields
users.toSorted((a, b) => b.age - a.age || a.name.localeCompare(b.name))
[ 'Asha', 'Li', 'Ravi', 'Sam' ]
The || operator is the trick: if the first comparison returns 0 (a tie), JavaScript evaluates the second one. Chain as many fields as you need: byCity || byAge || byName. This sorted by age descending, then by name alphabetically within each age.
Sorting dates
const dates = ["2026-03-01", "2025-12-31", "2026-01-15"].map(d => new Date(d));
console.log(dates.toSorted((a, b) => a - b).map(d => d.toISOString().slice(0, 10)));
[ '2025-12-31', '2026-01-15', '2026-03-01' ]
Subtracting two Date objects gives the difference in milliseconds, so the numeric pattern works directly. Dates stored as ISO strings like “2026-01-15” also sort correctly with plain string comparison, because the format puts the year first. Dates in “15/01/2026” style do not; convert them first.
undefined, NaN and mixed types
console.log([3, undefined, 1, , 2].sort((a, b) => a - b));
console.log([3, NaN, 1, 2].sort((a, b) => a - b));
console.log([10, "9", 8, "1"].sort());
console.log([10, "9", 8, "1"].sort((a, b) => a - b));
[ 1, 2, 3, undefined, <1 empty item> ]
[ 3, NaN, 1, 2 ]
[ '1', 10, 8, '9' ]
[ '1', 8, '9', 10 ]
undefined values and empty slots always move to the end and are never passed to your compare function. NaN is worse: a - NaN is NaN, which the sort treats like 0, and in our run the whole array stayed unsorted. Clean or filter your data before sorting. Mixed strings and numbers sort correctly with subtraction because - converts strings to numbers, but the safer fix is converting the data once with .map(Number).
The boolean compare bug
console.log([3, 1, 2, 5, 4].sort((a, b) => a > b));
[ 3, 1, 2, 5, 4 ]
Older tutorials sometimes show (a, b) => a > b. It returns true or false, which convert to 1 or 0, never a negative number. The sort never learns that one item should come first, and in our run nothing moved at all. Some engines happen to give a sorted result on small arrays, which is why this bug survives reviews. Always return a number.
Tip: if a compare function contains > or <, it must return -1, 1 or 0 explicitly, for example a > b ? 1 : a < b ? -1 : 0. For numbers, plain subtraction is simpler.
Is JavaScript sort stable?
Yes, since ES2019 the standard requires a stable sort: items that compare equal keep their original order. We sorted ten items by an even or odd group and got 0,2,4,6,8,1,3,5,7,9, with each group still in its original order. Stability lets you sort by a secondary field first and the primary field second, the same technique our Python sort list guide uses.
How fast is sorting?
We sorted one million random integers on Node 24:
| Method | Time | Correct numeric order? |
|---|---|---|
[...big].sort((a, b) => a - b) |
274 ms | Yes |
new Int32Array(big).sort() |
75 ms | Yes |
[...big].sort() (default) |
314 ms | No, string order |
Typed arrays such as Int32Array and Float64Array sort numerically by default and were about 3.6 times faster here, a useful trick for large numeric data. The broken default sort was also the slowest, because it converts every number to a string first.
Common mistakes
- No compare function for numbers. Always pass
(a, b) => a - b. - Mutating shared data. Use
toSorted()or copy first. - Returning a boolean. Return a number.
- Sorting text with > and <. Use
localeComparefor human-friendly order. - Sorting dirty data. Remove NaN and convert strings to numbers before sorting.
JavaScript sort array cheat sheet
| Goal | Code |
|---|---|
| Numbers ascending | arr.sort((a, b) => a - b) |
| Numbers descending | arr.sort((a, b) => b - a) |
| Without mutating | arr.toSorted(fn) |
| Strings, human order | arr.sort((a, b) => a.localeCompare(b)) |
| Natural order | localeCompare(b, undefined, {numeric: true}) |
| Objects by field | arr.sort((a, b) => a.age - b.age) |
| Several fields | (a, b) => a.x - b.x || a.y.localeCompare(b.y) |
| Dates | arr.sort((a, b) => a - b) |
| Reverse a sorted array | arr.toReversed() |
Final thoughts
JavaScript sort array problems almost always trace back to three defaults: items compare as strings, the original array is changed, and a compare function must return a number. Pass a numeric compare function, prefer toSorted() for shared data, use localeCompare for text, and clean your data first. Then sorting becomes as boring and reliable as it should be. For keyed data, our Map vs Object guide is a good next read.
Frequently asked questions
Why does JavaScript sort numbers incorrectly?
Without a compare function, sort converts numbers to strings and compares them as text, so 10 comes before 5. Pass (a, b) => a – b to sort numerically.
How do I sort an array of objects by a property in JavaScript?
Compare the property inside the function: arr.sort((a, b) => a.age – b.age) for numbers, or a.name.localeCompare(b.name) for strings.
Does sort() change the original array?
Yes. sort works in place and returns the same array. Use toSorted() or sort a copy made with the spread operator to keep the original unchanged.
How do I sort in descending order in JavaScript?
Reverse the subtraction: arr.sort((a, b) => b – a) for numbers, or b.localeCompare(a) for strings.
Is Array.prototype.sort stable?
Yes. Since ES2019 the specification requires a stable sort, so equal items keep their original relative order in all modern engines.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.