In this tutorial, we'll learn how to use the sort() method.
What does sort()
do?
You guessed it: The sort()
method sorts the elements of an array in-place and returns the sorted array.
Okay, but what does in-place mean, Basil? Simply put, in-place means that the original array is updated instead of a new one being created.
Let's take a look...
Syntax
// Function-less:
array.sort();
// Compare function:
array.sort(compareFunction);
// In-line compare function:
array.sort(function compareFunction(firstEl, secondEl) { ... });
// Arrow function:
array.sort((firstEl, secondEl) => { ... });
How does sort()
work?
By default, the sort()
method sorts the array elements in ascending order (i.e., from smallest to largest), but you can alphabetize or sort by ascending (up) or descending (down) values using a compare function.
compareFunction
The optional compareFunction
parameter specifies a function that defines an alternative sort order.
The function should take two parameters (firstEl
[the first element for comparison] and secondEl
[the second element for comparison]) and return a negative number if the first parameter should come first, a positive number if the second parameter should come first, and zero if the two parameters are equal (keep original order).
Syntax:
array.sort(function compareFunction(firstEl, secondEl) {
if (firstEl is less than secondEl) {
return -1;
}
else if (firstEl is greater than secondEl) {
return 1;
}
// firstEl is equal to secondEl
return 0;
});
Example
Let's say we have an array of objects:
let pokemon = [
{ "id": 4, "name": "Charmander", "type": "Fire" },
{ "id": 25, "name": "Pikachu", "type": "Electric" },
{ "id": 59, "name": "Arcanine", "type": "Fire" },
{ "id": 89, "name": "Muk", "type": "Poison" },
{ "id": 135, "name": "Jolteon", "type": "Electric" }
];
Currently, the Pokemon are sorted by their National Pokedex number (or id
); however, we want to sort them by their type
.
To do this, let's create a compare function comparing the type
property of each object.
pokemon.sort((firstEl, secondEl) => {
if (firstEl.type.toLowerCase() < secondEl.type.toLowerCase()) {
return -1;
} else if (firstEl.type.toLowerCase() > secondEl.type.toLowerCase()) {
return 1;
} else {
return 0;
}
});
Output:
[
{ id: 25, name: 'Pikachu', type: 'Electric' },
{ id: 135, name: 'Jolteon', type: 'Electric' },
{ id: 4, name: 'Charmander', type: 'Fire' },
{ id: 59, name: 'Arcanine', type: 'Fire' },
{ id: 89, name: 'Muk', type: 'Poison' }
]
Now, the objects in the array are sorted alphabetically by their type
property.
It's as easy as that!
Important!
The sort()
method converts elements to strings first and then compares the strings to determine the orders.
So what, you ask?
Well, let's take a look at this array of values:
let numbers = [1, 123, 12, 21, 77, 41];
If you were to use the sort()
method on the above array (numbers
) without specifying a compare function, you'd get the following output:
[ 1, 12, 123, 21, 41, 77 ]
That doesn't look right...
Remember: When sorting numerical values, you must specify a compare function. For example:
numbers.sort((a, b) => a - b));
// Output: [ 1, 12, 21, 41, 77, 123 ]
Resources
For more information on and examples of sort()
method's uses, visit: MDN Web Docs.
Top comments (0)