Sorting is a fundamental operation in programming. In JavaScript, sorting can be performed on arrays using built-in methods and custom logic. This guide covers the essentials and advanced techniques for sorting in JavaScript, with detailed examples and step-by-step explanations.
1. Sorting Basics with sort()
The sort()
method sorts the elements of an array in place and returns the sorted array. By default, sort()
converts elements to strings and compares their UTF-16 code unit values.
Example: Sorting Strings
const fruits = ["Banana", "Apple", "Cherry"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Cherry"]
Explanation:
The
sort()
method is called on thefruits
array.Each element in the array is converted to a string if it isn't already.
The strings are compared based on their UTF-16 code unit values.
The array is modified in place, so the original array is now sorted alphabetically.
2. Numeric Sorting
Since sort()
converts elements to strings by default, sorting numbers requires a comparison function.
Example: Sorting Numbers
const numbers = [10, 2, 5, 1];
// Ascending order
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 10]
// Descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // [10, 5, 2, 1]
Step-by-Step (Ascending Order):
The
sort()
method is called with a comparison function(a, b) => a - b
.The comparison function subtracts
b
froma
:If the result is negative,
a
comes beforeb
.If the result is zero, their order is unchanged.
If the result is positive,
b
comes beforea
.
The array is sorted in ascending order.
Step-by-Step (Descending Order):
The comparison function is changed to
(a, b) => b - a
.This reverses the logic, so larger numbers are placed before smaller ones.
3. Custom Sorting with compareFunction
The compareFunction
allows custom sorting logic by comparing two elements a
and b
.
Example: Sorting Strings by Length
const words = ["apple", "kiwi", "banana", "cherry"];
words.sort((a, b) => a.length - b.length);
console.log(words); // ["kiwi", "apple", "banana", "cherry"]
Explanation:
The
compareFunction
calculates the difference in length between two strings.- For example,
"apple".length - "kiwi".length
evaluates to5 - 4 = 1
.
- For example,
Positive results place
b
beforea
.Negative results place
a
beforeb
.The array is sorted by the length of each string.
4. Sorting Objects
Objects can be sorted by their properties using a custom compareFunction
.
Example: Sorting by Age
const people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 20 }
];
people.sort((a, b) => a.age - b.age);
console.log(people);
Explanation:
The
compareFunction
accesses theage
property of each object.It subtracts
b.age
froma.age
:- For example,
{ name: "Alice", age: 25 }
and{ name: "Charlie", age: 20 }
will evaluate as25 - 20 = 5
.
- For example,
The array is sorted in ascending order based on the
age
property.The result is:
[ { name: "Charlie", age: 20 }, { name: "Alice", age: 25 }, { name: "Bob", age: 30 } ]
5. Stable Sorting
JavaScript's sort()
method is stable (since ECMAScript 2019). Stable sorting maintains the relative order of elements that are equal.
Example:
const items = [
{ name: "item1", value: 10 },
{ name: "item2", value: 20 },
{ name: "item3", value: 10 }
];
items.sort((a, b) => a.value - b.value);
console.log(items);
Explanation:
The
compareFunction
compares thevalue
property.Items with the same
value
retain their original order.Result:
[ { name: "item1", value: 10 }, { name: "item3", value: 10 }, { name: "item2", value: 20 } ]
6. Using localeCompare()
for Internationalization
The localeCompare()
method is useful for sorting strings in a locale-aware manner.
Example:
const names = ["Émile", "Emma", "Eve"];
names.sort((a, b) => a.localeCompare(b));
console.log(names); // ["Emma", "Eve", "Émile"]
Explanation:
localeCompare()
compares strings based on the current locale settings.This ensures proper sorting of special characters and accents.
7. Case-Insensitive Sorting
To sort strings case-insensitively, use toLowerCase()
in the compareFunction
.
Example:
const cities = ["paris", "London", "new york", "Amsterdam"];
cities.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
console.log(cities); // ["Amsterdam", "London", "new york", "paris"]
Explanation:
The
toLowerCase()
method converts each string to lowercase.The
localeCompare()
method compares the strings in a locale-aware manner.
8. Performance Considerations
Sorting is O(n log n) on average.
Sorting large arrays can impact performance, so optimizing the
compareFunction
to avoid unnecessary computations.
Example:
const largeArray = Array.from({ length: 100000 }, () => Math.random());
largeArray.sort((a, b) => a - b);
Explanation:
A large array of random numbers is created using
Array.from()
.The
sort()
method efficiently sorts the array in ascending order.
Hope that helps.