JavaScript Array.sort() Method - Sorting Arrays Correctly
Master Array.sort() with compare functions for numbers, strings, objects, and dates. Covers the default string sort pitfall and toSorted() (ES2023). Free reference.
Detailed Explanation
Understanding Array.sort()
Array.sort() sorts elements in place and returns the sorted array. Without a compare function, elements are converted to strings and sorted by UTF-16 code unit order.
The Default Sort Pitfall
// WRONG — default sorts as strings!
[10, 1, 21, 2].sort();
// Result: [1, 10, 2, 21] (string order)
// CORRECT — use a compare function for numbers
[10, 1, 21, 2].sort((a, b) => a - b);
// Result: [1, 2, 10, 21]
Compare Function Rules
The compare function must return:
- Negative if a should come before b
- Zero if they are equal
- Positive if a should come after b
// Ascending numbers
arr.sort((a, b) => a - b);
// Descending numbers
arr.sort((a, b) => b - a);
// Alphabetical strings (locale-aware)
arr.sort((a, b) => a.localeCompare(b));
// Sort objects by property
users.sort((a, b) => a.name.localeCompare(b.name));
// Sort by date
events.sort((a, b) => new Date(a.date) - new Date(b.date));
Stability
As of ES2019, sort() is guaranteed to be stable — elements that compare equal retain their original relative order.
sort() Mutates!
sort() modifies the original array. If you need to preserve the original:
// Pre-ES2023 workaround
const sorted = [...arr].sort((a, b) => a - b);
// ES2023: toSorted()
const sorted = arr.toSorted((a, b) => a - b);
// arr is unchanged
Performance
sort() uses an implementation-dependent algorithm (usually TimSort in V8/SpiderMonkey), with O(n log n) average-case complexity. For very large arrays (100k+ elements), consider whether you actually need a full sort or just the top N elements.
Use Case
Use sort() for ordering lists alphabetically, sorting tables by column, arranging items by date or priority, and implementing custom ordering logic. Use toSorted() in React state updates where immutability is required.