JavaScript sort() method for beginners
Explained step-by-step, using different examples.
(╯°□°)╯ .sort()
The sort()
function is used to sort data within an array or an array of objects.
Example 1
When you want sort numbers from lowest to highest. It is as easy as just using the .sort()
function . This is an array of numbers.
const num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const lowToHighNum = num.sort();
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
When you want to sort the numbers from highest to lowest, make use of an if
function (also called the ternary operator). If a is bigger than b, return -1. If a is smaller than b, return +1.
const highToLowNum = num.sort((a, b) => {
if (a > b) {
return -1;
}
if (a < b) {
return +1;
}
else {
return 0;
}
});
// [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
Example 2
When you want to sort a string in an array alphabetically. It is also as easy as just using the .sort()
function.
const letters = ["c", "m", "a", "p", "b", "f"];
const orderLetters = letters.sort();
// [ "a", "b", "c", "f", "m", "p" ]
When you want to sort the array in an achronological manner, use the ternary operator (if
statement).
const orderLetters = letters.sort((a, b) => {
if (a > b) {
return -1;
}
if (a < b) {
return +1;
} else {
return 0;
}
});
// [ "p", "m", "f", "c", "b", "a" ]
Example 4
When we want to sort an array of objects. Here we have an object of food.
const food = [
{ name: "apple", healthy: true },
{ name: "pizza", healthy: false },
{ name: "broccoli", healthy: true },
];
We want to order the food names alphabetically within the array of objects.
const orderFood = food.sort((a, b) => {
if (a.name > b.name) {
return +1;
}
if (a.name < b.name) {
return -1;
} else {
return 0;
}
});
// { name: "apple", healthy: true }
// { name: "broccoli", healthy: true }
// { name: "pizza", healthy: false }