Skip to content

sort()

sort() sorts elements in place and returns the sorted array. By default, it converts elements to strings and sorts lexicographically.

[3, 30, 1, 100].sort();
// [1, 100, 3, 30] — string order!
// 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]
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);
  • Default sort is lexicographic (string-based)
  • Always provide a comparator function for numbers
  • Mutates the original array — copy first if needed