The JavaScript sort()
method is used to sort the elements of an array in place, meaning it modifies the original array. By default, it sorts the elements as strings in lexicographical (dictionary) order. However, you can also provide a custom sorting function to sort the elements in a different order.
Syntax:
array.sort([compareFunction]);
array
: The array to be sorted.compareFunction
(optional): A function that defines the sort order. If omitted, the array is sorted as strings.
Example 1: Default Sorting (Lexicographical Order)
The default behavior of sort()
sorts the array elements as strings. For example:
let fruits = ['banana', 'apple', 'cherry', 'date'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']
Even though the array contains fruit names, it is sorted based on the lexicographical order of the string values.
Example 2: Sorting Numbers (with compareFunction
)
When sorting numbers, the default behavior of sort()
doesn’t work as expected because the method compares values as strings. To sort numbers numerically, you need to provide a compare function.
The compare function takes two arguments (a
and b
), and:
- Returns a negative value if
a
should come beforeb
. - Returns a positive value if
a
should come afterb
. - Returns
0
ifa
andb
are equal.
Ascending Order (Smallest to Largest):
let numbers = [5, 3, 8, 1, 2];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 3, 5, 8]
Descending Order (Largest to Smallest):
let numbers = [5, 3, 8, 1, 2];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [8, 5, 3, 2, 1]
Example 3: Sorting Strings with Custom Compare Function
You can also provide a custom compare function to control the order of elements based on specific rules.
Case-Insensitive Sorting:
let words = ['banana', 'Apple', 'cherry', 'Date'];
words.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(words); // Output: ['Apple', 'banana', 'cherry', 'Date']
Here, localeCompare
is used to compare strings in a case-insensitive manner.
Example 4: Sorting Objects Based on a Property
You can also sort an array of objects based on a specific property.
Sorting Objects by Age:
let people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
people.sort((a, b) => a.age - b.age);
console.log(people);
// Output: [
// { name: 'Charlie', age: 20 },
// { name: 'Alice', age: 25 },
// { name: 'Bob', age: 30 }
// ]
In this case, the array of objects is sorted by the age
property in ascending order.
Example 5: Sorting Alphabetically (Case-Insensitive)
You can sort an array of strings in a case-insensitive manner by using localeCompare()
inside a custom compare function:
let cities = ['Paris', 'amsterdam', 'New York', 'london'];
cities.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(cities); // Output: ['amsterdam', 'London', 'New York', 'Paris']
Key Points:
- In-place sorting: The
sort()
method sorts the original array and does not return a new array. - Default sorting: If no compare function is provided, it sorts elements as strings based on Unicode values.
- Custom sorting: You can define a custom compare function to sort elements in a specific order (e.g., numerical, alphabetical).
- Stability: As of ECMAScript 2019 (ES10), the
sort()
method is stable, meaning it preserves the relative order of equal elements.
Conclusion:
The sort()
method is a powerful tool for sorting arrays in JavaScript. By providing a custom compare function, you can sort arrays based on any logic, including numerical or case-insensitive sorting.