Array.sort() Sort in place
Last updated: 2026-09-09
Array.sort() Sort in place
Default sort converts to strings — 10 comes before 9! Pass a comparator for numbers.
| Category | Arrays |
|---|---|
| ES version | ES1 (1997) |
📝 Syntax
array.sort();
array.sort((a, b) => a - b);
⚙️ Parameters
| compareFn | Negative keeps a first, positive keeps b first, 0 preserves order. |
|---|
Returns:The same array, sorted.
Mutates the original:Yes (in place)
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
[ 1, 10, 100, 9 ]
[ 1, 9, 10, 100 ]
[ 100, 10, 9, 1 ]
Li
⚠️ Warning Default sort is lexicographic: [10, 9] stays [10, 9] — always pass a comparator for numbers.
💡 Tip sort mutates — use toSorted() (ES2023) or [...arr].sort() for a copy.
ℹ️ info Negative keeps a first, positive keeps b first, 0 preserves order (stable since ES2019).
🌐 Browser support
| Browser | |||||
|---|---|---|---|---|---|
| Array.sort() | ✓ v1 | ✓ v12 | ✓ v1.5 | ✓ v3 | ✓ v10.5 |
| Supported by all modern browsers | |||||
🏷️ Related Array Methods
💡 Related Cases
More case studies coming soon — check back later.
📚 Related Tutorials
❓ FAQ
QWhy does [10, 9, 100] sort wrong?
ADefault compare converts to strings: '10' < '100' < '9'. Use (a, b) => a - b for numbers.
QDoes sort mutate?
AYes — use [...arr].sort(cmp) or arr.toSorted(cmp).
QSorting objects by string property?
AUse a.name.localeCompare(b.name) — it handles Chinese and accents correctly.