JavaScript Array Sort
JavaScript Array Sort
JavaScript provides several methods to sort arrays — either alphabetically, numerically, or using custom conditions.
1. sort() – Default Sorting
The sort() method sorts elements alphabetically by default.
Output:
⚠ Note: Default
sort()converts elements to strings, so numbers may not sort as expected.
2. Sorting Numbers Correctly
For numbers, use a compare function:
3. reverse() – Reverse Array
Output:
4. Sorting Array of Objects
5. localeCompare() – Sort Strings with Accents
Output:
Summary Table
| Method | Action |
|---|---|
sort() |
Default sort (alphabetical) |
sort((a,b)=>a-b) |
Numerical ascending |
sort((a,b)=>b-a) |
Numerical descending |
reverse() |
Reverse array order |
localeCompare() |
Sort strings properly with locale support |
