Introduction
Sorting arrays in JavaScript is a common task that can be accomplished using a variety of methods. In this article, we'll take a look at some of the different ways you can sort an array in JavaScript.
One of the most basic ways to sort an array is using the Array.sort()
method. This method sorts the elements of an array in place and returns the sorted array. By default, the sort()
method sorts the elements alphabetically or numerically, depending on the type of the elements.
In this article, we will explain ways to sorting array in JavaScript.
Typical sorting approach
We can use the sort()
method for simple to complex operations. Here's an example of how you might use the sort()
method to sort an array of numbers:
let numbers = [4, 2, 5, 1, 3];
numbers.sort();
console.log(numbers);
Output
[ 1, 2, 3, 4, 5 ]
If you want to sort the elements in a different order, such as descending order, you can pass a compare function as an argument to the sort()
method. The compare function should take two arguments and return a negative number if the first argument should come before the second, a positive number if the first argument should come after the second, and 0 if they are equal.
Sorting using a compare function
Here's an example of how you might use a compare function to sort an array of numbers in descending order:
let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[ 5, 4, 3, 2, 1 ]
Just like we have seen above, we can specify a custom compare function that can take into account more complex sorting criteria.
Here's an example of how you might use the sort()
method to sort an array of objects by a specific property:
let books = [
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ title: "To Kill a Mockingbird", author: "Harper Lee" },
{ title: "Pride and Prejudice", author: "Jane Austen" },
];
books.sort((a, b) => {
if (a.title < b.title) {
return -1;
}
if (a.title > b.title) {
return 1;
}
return 0;
});
console.log(books);
Output
[
{ title: 'Pride and Prejudice', author: 'Jane Austen' },
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee' }
]
In the example above, when the sort()
method is called, the books
array is sorted in ascending order by the title
property of each object. The sorted array is then logged to the console using the console.log()
function.
The if
statements in the compare function check whether the title
property of a
is less than, greater than, or equal to the title
property of b
. If the title
property of a
is less than the title
property of b
, the function returns -1, indicating that a
should come before b
. If the title
property of a
is greater than the title
property of b
, the function returns 1, indicating that a
should come after b
. If the title
properties are equal, the function returns 0, indicating that the order of the elements doesn't matter.
Sorting an array of numbers
To sort an array of numbers in ascending order, you can simply call the sort()
method on the array and pass in a compare function as an argument. The compare function should take two arguments, a
and b
, and return a negative number if a
should be placed before b
, a positive number if a
should be placed after b
, and 0 if a
and b
are equal.
Here is how we can sort an array of numbers in ascending order
let numbers = [25, 32, 14, 35, 44];
numbers.sort((a, b) => a - b);
console.log(numbers)
Output
[ 14, 25, 32, 35, 44 ]
Now, if you want to sort the array in descending order, you can simply reverse the order of the arguments in the compare function:
let numbers = [25, 32, 14, 35, 44];
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[ 44, 35, 32, 25, 14 ]
It's also worth noting that the sort()
method mutates the original array, so if you want to preserve the original array, you should make a copy of it before sorting. You can do this using the slice()
method:
let numbers = [25, 32, 14, 35, 44];
let sortedNumbers = numbers.slice().sort((a, b) => a - b);
console.log(numbers);
console.log(sortedNumbers);
Output
[ 25, 32, 14, 35, 44 ]
[ 14, 25, 32, 35, 44 ]
Sorting an array of strings
To sort an array of strings in alphabetical order, you can simply call the sort()
method on the array and pass in a compare function as an argument. The compare function should take two arguments, a
and b
, and return a negative number if a
should be placed before b
, a positive number if a
should be placed after b
, and 0 if a
and b
are equal.
Let’s illustrate sorting array of strings in JavaScript
let words = ["cherry", "apple", "blueberry"];
words.sort((a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
console.log(words);
Output
[ 'apple', 'blueberry', 'cherry' ]
If you want to sort the array in reverse alphabetical order, you can simply reverse the order of the arguments in the compare function:
let words = ["cherry", "apple", "blueberry"];
words.sort((a, b) => {
if (a > b) {
return -1;
}
if (a < b) {
return 1;
}
return 0;
});
console.log(words);
Output
[ 'cherry', 'blueberry', 'apple' ]
Just as with sorting numbers, the sort()
method mutates the original array, so if you want to preserve the original array, you should make a copy of it before sorting. You can do this using the slice()
method:
let words = ["cherry", "apple", "blueberry"];
let sortedWords = words.slice().sort((a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
console.log(words);
console.log(sortedWords);
Output
[ 'cherry', 'apple', 'blueberry' ]
[ 'apple', 'blueberry', 'cherry' ]
Sorting an array of strings with non-ASCII characters
Sorting an array of strings with non-ASCII characters in JavaScript can be a bit more complex, as the default sorting behavior of the sort()
method is based on the ASCII code of the characters, rather than their Unicode values. This can lead to incorrect sorting results for certain characters, such as accented letters or characters from non-Latin scripts.
To correctly sort an array of strings with non-ASCII characters, you can use the localeCompare()
method, which compares two strings based on the Unicode values of their characters, taking into account the specified locale.
To use localeCompare()
, you can pass a compare function to the sort()
method that uses localeCompare()
to compare the two arguments. Let’s illustrate how to sort an array with non-ASCII characters.
let words = ["cherry", "apple", "blueberry", "éclair"];
words.sort((a, b) => a.localeCompare(b));
console.log(words);
Output
[ 'apple', 'blueberry', 'cherry', 'éclair' ]
This will sort the words
array in alphabetical order, taking into account the Unicode values of the characters and considering the default locale.
If you want to specify a different locale, you can pass it as the first argument to localeCompare()
. Here, we will pass the locale of fr-FR
represent French to determine how it will be sort.
let words = ["cherry", "apple", "blueberry", "éclair"];
words.sort((a, b) => a.localeCompare(b, "fr-FR"));
console.log(words);
Output
[ 'apple', 'blueberry', 'cherry', 'éclair' ]
This will sort the words
array in alphabetical order, taking into account the Unicode values of the characters and considering the French (France) locale.
Sorting objects by a string property
To sort an array of objects by a string property, you can pass a compare function to the sort()
method that compares the values of the desired property for each object. For example, consider an array of objects representing people, each with a name
property:
let people = [{ name: "Amaka" }, { name: "Zainab" }, { name: "Evelyn" }];
people.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
console.log(people);
Output
[ { name: 'Amaka' }, { name: 'Evelyn' }, { name: 'Zainab' } ]
This will sort the people
array in alphabetical order based on the name
property of each object.
If you want to sort the array in reverse alphabetical order, you can simply reverse the order of the arguments in the compare function:
let people = [{ name: "Amaka" }, { name: "Zainab" }, { name: "Evelyn" }];
people.sort((a, b) => {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
return 0;
});
console.log(people);
Output
[ { name: 'Zainab' }, { name: 'Evelyn' }, { name: 'Amaka' } ]
It's also worth noting that the sort()
method mutates the original array, so if you want to preserve the original array, you should make a copy of it before sorting. You can do this using the slice()
method:
let people = [{ name: "Amaka" }, { name: "Zainab" }, { name: "Evelyn" }];
let sortedPeople = people.slice().sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
console.log(people);
console.log(sortedPeople);
Output
[ { name: 'Amaka' }, { name: 'Zainab' }, { name: 'Evelyn' } ]
[ { name: 'Amaka' }, { name: 'Evelyn' }, { name: 'Zainab' } ]
Sorting objects by a numeric property
To sort an array of objects by a numeric property, you can pass a compare function to the sort()
method that compares the values of the desired property for each object.
For example, consider an array of objects representing products, each with a price
property:
let products = [{ price: 10 }, { price: 5 }, { price: 15 }];
products.sort((a, b) => a.price - b.price);
console.log(products);
Output
[ { price: 5 }, { price: 10 }, { price: 15 } ]
This will sort the products
array in ascending order based on the price
property of each object.
If you want to sort the array in descending order, you can simply reverse the order of the arguments in the compare function:
let products = [{ price: 10 }, { price: 5 }, { price: 15 }];
products.sort((a, b) => b.price - a.price);
console.log(products);
Output
[ { price: 15 }, { price: 10 }, { price: 5 } ]
It's also worth noting that the sort()
method mutates the original array, so if you want to preserve the original array, you should make a copy of it before sorting. You can do this using the slice()
method:
let products = [{ price: 10 }, { price: 5 }, { price: 15 }];
let sortedProducts = products.slice().sort((a, b) => a.price - b.price);
console.log(products);
console.log(sortedProducts);
Output
[ { price: 10 }, { price: 5 }, { price: 15 } ]
[ { price: 5 }, { price: 10 }, { price: 15 } ]
Summary
Overall, sorting arrays in JavaScript is a common and important task that can be accomplished using a variety of methods. Whether you use the built-in sort()
method or a utility function from a library, there are many options available to help you in sorting arrays in JavaScript just the way you need it.
References
Array.prototype.sort() - JavaScript | MDN (mozilla.org)