When sorting arrays in JavaScript, you might expect [4, 11, 2, 23].sort()
to return [2, 4, 11, 23]
. Surprisingly, the result is [11, 2, 23, 4]
. Let’s explore why this happens, and how Unicode code points factor into the comparison.
Default Sort Behavior
By default, JavaScript’s Array.prototype.sort()
method sorts elements as strings in ascending Unicode order. This means each array element is converted to a string, and the comparison is made based on these string values, character by character.
Let’s see the array as strings:
"4"
"11"
"2"
"23"
When comparing these strings, JavaScript looks at the first character of each string and compares their Unicode code points:
String | First Character | Unicode Code Point |
---|---|---|
"4" | '4' | 52 |
"11" | '1' | 49 |
"2" | '2' | 50 |
"23" | '2' | 50 |
-
"11" vs. "2":
- '1' (code 49) vs. '2' (code 50) ⇒ 49 < 50 ⇒
"11"
comes before"2"
.
- '1' (code 49) vs. '2' (code 50) ⇒ 49 < 50 ⇒
-
"2" vs. "23":
- Both start with '2' (code 50). Then
"2"
ends, while"23"
continues with another '3'. - By string comparison rules, a shorter string that is a prefix of a longer one is considered smaller ⇒
"2"
comes before"23"
.
- Both start with '2' (code 50). Then
-
"23" vs. "4":
- '2' (code 50) vs. '4' (code 52) ⇒ 50 < 52 ⇒
"23"
comes before"4"
.
- '2' (code 50) vs. '4' (code 52) ⇒ 50 < 52 ⇒
Ultimately, as strings, the sorted order is "11" < "2" < "23" < "4"
, which corresponds to [11, 2, 23, 4]
when converted back to numbers in the array.
How to Fix It (Sort Numerically)
If you want to sort numbers in numeric order, you need to provide a compare function to the sort()
method. This compare function tells JavaScript how to compare two elements numerically instead of as strings:
[4, 11, 2, 23].sort((a, b) => a - b);
// [2, 4, 11, 23]
- If
a - b
is negative, a comes before b. - If
a - b
is zero, the order of a and b stays as is. - If
a - b
is positive, a comes after b.
Key Takeaways
- Default String Comparison: JavaScript’s default sort() converts elements to strings and sorts them in ascending Unicode order.
- Numeric Sorting: To sort numbers, provide a compare function—(a, b) => a - b.
Armed with this knowledge, you can confidently sort arrays in JavaScript, whether you need to sort them as strings or numbers.
Console You Later!
Top comments (0)