sort() in an array
The sort() method in JavaScript is used to sort the elements of an array.
It mutates the original array (unlike most other methods) and can work with both numbers and strings if you provide a compare function.
Syntax
array.sort(compareFunction);Where compareFunction is a callback of the form:
(a, b) => {
// return a negative value if a should come before b
// return a positive value if a should come after b
// return 0 if the order doesn't matter
}Example 1. Simple string sorting
const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'cherry']By default
sort()sorts elements as Unicode strings, even if they are numbers! That's why numbers without a callback are sorted not by magnitude, but by character.
Example 2. A mistake when sorting numbers without a compare function
const numbers = [1, 10, 2, 5];
numbers.sort();
console.log(numbers); // [1, 10, 2, 5] - sorted as strings!Fixed:
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 10]The function
(a, b) => a - bsorts in ascending order,(a, b) => b - a- in descending order.
Example 3. Sorting by an object property
const users = [
{ name: 'Tim', age: 25 },
{ name: 'Alex', age: 30 },
{ name: 'John', age: 20 }
];
users.sort((a, b) => a.age - b.age);
console.log(users);
// [
// { name: 'John', age: 20 },
// { name: 'Tim', age: 25 },
// { name: 'Alex', age: 30 }
// ]A common scenario is sorting an array of objects by a numeric field.
Example 4. Sorting strings alphabetically (case-insensitive)
const names = ['tim', 'Alex', 'john'];
names.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
console.log(names); // ['Alex', 'john', 'tim']
localeCompareis the correct way to sort strings taking language and case into account.
Example 5. Sorting in descending order
const prices = [100, 500, 200, 50];
prices.sort((a, b) => b - a);
console.log(prices); // [500, 200, 100, 50]Important: sort() mutates the original array
const arr = [3, 1, 2];
const sorted = arr.sort();
console.log(sorted); // [1, 2, 3]
console.log(arr); // [1, 2, 3] - the same array, mutated!If you need to keep the original array, copy it before sorting:
const sortedCopy = [...arr].sort((a, b) => a - b);Example 6. Sorting by multiple criteria
const users = [
{ name: 'Tim', age: 25 },
{ name: 'Alex', age: 25 },
{ name: 'John', age: 20 }
];
users.sort((a, b) => {
if (a.age !== b.age) return a.age - b.age;
return a.name.localeCompare(b.name);
});
console.log(users);
// [
// { name: 'John', age: 20 },
// { name: 'Alex', age: 25 },
// { name: 'Tim', age: 25 }
// ]If the age is the same, sorting falls back to the name.
Mistakes to watch for
- Without a callback, strings are sorted instead of numbers
[10, 2, 1].sort(); // ['1', '10', '2']Solution:
[10, 2, 1].sort((a, b) => a - b); // [1, 2, 10]- Mutating the original array
const a = [3, 1, 2];
const b = a.sort();
console.log(a === b); // true - it's the same object- Lack of stability in older JS versions
Sorting could be unstable in older engines (before ES2019). In modern ECMAScript versions
sort()is stable - elements with equal order keep their original relative position.
When to use sort()
| Goal | Is sort() suitable? |
|---|---|
| Sort numbers or strings | Yes |
| Sort objects by a field | Yes |
| Get a new sorted array without changing the original | Yes, but only with a copy ([...arr]) |
| Check a condition | No |
| Transform data | No |
In short:
sort()sorts the elements of an array in place, by default as strings. To sort numbers, provide a compare function.
Memorization formula:
arr.sort((a, b) => a - b) -> ascending
arr.sort((a, b) => b - a) -> descending
Comparison with other methods
| Method | Returns a new array | Mutates the original | Purpose |
|---|---|---|---|
| map() | yes | no | Transforms elements |
| filter() | yes | no | Selects elements |
| find() | no (an element) | no | Finds the first matching element |
| reduce() | no (a single value) | no | Reduces to a single result |
| sort() | no (the same array) | yes | Sorts elements |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.