DEV Community

Cover image for JavaScript Can't Sort Numbers?! [10, 1, 5, 100].sort() Explained
Muiduzzaman Lipu for Refactorly

Posted on

JavaScript Can't Sort Numbers?! [10, 1, 5, 100].sort() Explained

10, 1, 5, 100. Sort them in JavaScript and you get 1, 10, 100, 5.

That's not a bug in JavaScript; it's how sort() is specified. And it's not the only trap. Here are all of them, with fixes. Every output below was run in Node.js 22.

Video version:

Trap 1: sort() compares strings

[10, 1, 5, 100].sort()   // [ 1, 10, 100, 5 ]  ❌
[-1, -10, 2].sort()      // [ -1, -10, 2 ]     ❌
"10" < "5"               // true
Enter fullscreen mode Exit fullscreen mode

Without a compare function, sort() converts every item to a string and compares them like words in a dictionary. As text, "10" comes before "5" because the first character, 1, is smaller than 5.

The fix: a compare function

nums.sort((a, b) => a - b);  // ascending:  [ 1, 5, 10, 100 ] ✅
nums.sort((a, b) => b - a);  // descending: [ 100, 10, 5, 1 ]
Enter fullscreen mode Exit fullscreen mode

The compare function returns a number:

  • negative: a goes first
  • positive: b goes first
  • zero: keep their order (sort is stable)

Trap 2: returning true / false

[5, 1, 4, 2, 3].sort((a, b) => a > b)   // [ 5, 1, 4, 2, 3 ]  ❌ not sorted
[5, 1, 4, 2, 3].sort((a, b) => a - b)   // [ 1, 2, 3, 4, 5 ]  ✅
Enter fullscreen mode Exit fullscreen mode

a > b returns a boolean. true becomes 1 and false becomes 0, which means "equal". The result is never negative, so the array doesn't get sorted. It can look like it works on some inputs, which makes this bug sneaky. Always return a number.

Trap 3: sort() changes the original array

const prices = [30, 5, 20];
const sorted = prices.sort((a, b) => a - b);

prices            // [ 5, 20, 30 ]  😱 original changed
sorted === prices // true
Enter fullscreen mode Exit fullscreen mode

sort() sorts in place and returns the same array, not a copy. That's a classic bug in React state, and anywhere else the original order is still needed.

The fix: toSorted()

const prices = [30, 5, 20];
const sorted = prices.toSorted((a, b) => a - b);

prices   // [ 30, 5, 20 ]  ✅ untouched
sorted   // [ 5, 20, 30 ]
Enter fullscreen mode Exit fullscreen mode

toSorted() (ES2023) takes the same arguments but returns a new array. It works in all modern browsers and Node 20+. Its siblings are toReversed(), toSpliced() and with().

Sorting text: localeCompare

const words = ["banana", "apple", "Cherry", "éclair", "zebra"];

words.toSorted()
// [ 'Cherry', 'apple', 'banana', 'zebra', 'éclair' ]  ❌

words.toSorted((a, b) => a.localeCompare(b))
// [ 'apple', 'banana', 'Cherry', 'éclair', 'zebra' ]  ✅
Enter fullscreen mode Exit fullscreen mode

The default sort compares UTF-16 code units, so uppercase letters come before lowercase and accented letters end up at the end. localeCompare sorts the way people read.

For names with numbers in them, add numeric: true:

const files = ["file10.txt", "file2.txt", "file1.txt"];

files.toSorted((a, b) => a.localeCompare(b))
// [ 'file1.txt', 'file10.txt', 'file2.txt' ]  ❌

files.toSorted((a, b) => a.localeCompare(b, undefined, { numeric: true }))
// [ 'file1.txt', 'file2.txt', 'file10.txt' ]  ✅
Enter fullscreen mode Exit fullscreen mode

Sorting objects by two keys

const users = [
  { name: "Cy",  age: 30 },
  { name: "Ann", age: 25 },
  { name: "Bo",  age: 30 },
];

users.toSorted((a, b) => b.age - a.age || a.name.localeCompare(b.name));
// Bo 30, Cy 30, Ann 25
Enter fullscreen mode Exit fullscreen mode

Oldest first (b.age - a.age). When the ages are equal, the result is 0, which is falsy, so || moves on to the next rule: the name. (|| is exactly right here, because 0 is the value you want to skip. Compare that with default values, where || is a bug.)

Cheat sheet

Task Code
Numbers, ascending (a, b) => a - b
Numbers, descending (a, b) => b - a
Keep the original array arr.toSorted(…)
Text (a, b) => a.localeCompare(b)
File names / versions a.localeCompare(b, undefined, { numeric: true })
Two keys `byFirst(a, b) \

And never return {% raw %}a > b.

Has sort() ever surprised you? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (0)