sort()
sort()
Section titled “sort()”Introduction
Section titled “Introduction”sort() sorts elements in place and returns the sorted array. By default, it converts elements to strings and sorts lexicographically.
Default Sort (String Order)
Section titled “Default Sort (String Order)”[3, 30, 1, 100].sort();// [1, 100, 3, 30] — string order!Custom Comparator
Section titled “Custom Comparator”// Numeric ascending[3, 30, 1, 100].sort((a, b) => a - b);// [1, 3, 30, 100]
// Numeric descending[3, 30, 1, 100].sort((a, b) => b - a);// [100, 30, 3, 1]Objects
Section titled “Objects”const users = [ { name: 'Charlie', age: 30 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 35 }];
users.sort((a, b) => a.name.localeCompare(b.name));users.sort((a, b) => a.age - b.age);Summary
Section titled “Summary”- Default sort is lexicographic (string-based)
- Always provide a comparator function for numbers
- Mutates the original array — copy first if needed