JavaScript Array Sort

JavaScript Array Sort — Complete Detailed Guide
In JavaScript Array Sort is used to arrange array elements. It works for strings, numbers, objects, and dates, but understanding how it works internally is very important.
Basic Syntax
compareFunction→ optionalIf not provided, elements are converted to strings and sorted in lexicographical (dictionary) order
Default Sorting (Strings)
Example: Alphabetical Order
Works correctly because elements are strings.
Case Sensitivity Issue
Reason: Capital letters have smaller ASCII/UTF-16 values.
Case-Insensitive Sorting
Sorting Numbers (MOST IMPORTANT)
Wrong Way (Common Mistake)
Numbers are treated as strings.
Correct Way (Ascending Order)
Descending Order
How compareFunction Works
JavaScript checks:
Negative value →
acomes beforebPositive value →
bcomes beforea0 → order remains unchanged
| Return Value | Meaning |
|---|---|
< 0 | a before b |
> 0 | b before a |
0 | no change |
Sorting Arrays of Objects
Example: Sort by Age
Sort by Name
Reverse Sorting
reverse() also mutates the original array.
Sort Without Modifying Original Array
sort() changes the original array.
Solution: Copy first
Sorting Dates
Real-World Use Cases
Leaderboard Ranking
E-commerce Price Sorting
Time Complexity
Average: O(n log n)
Exact algorithm depends on JavaScript engine (V8, SpiderMonkey, etc.)
Important Notes
sort()is in-place (mutates array)Default sort is string-based
Always use a compare function for numbers
Modern JS engines use stable sorting
