JavaScript's Built-in sort Method
The sort Method:
The sort method is designed to sort elements within an array in ascending order by default. The basic syntax is:
array.sort();
sort method modifies the original array in place, meaning it directly alters the array rather than creating a new one.
Sorting Strings:
String sorting is just as effortless with the sort method. Take a look at the following example:
const fruits = ["apple", "banana", "kiwi", "cherry", "fig", "date"]; fruits.sort();
console.log(fruits);
Executing this code gives the following output:
["apple", "banana", "cherry", "date", "fig", "kiwi"]
Sorting Numbers:
For sorting the numbers, we can't only use .sort(). Let's see why...
Let's say we want to sort the given array.
const numbers = [4, 21, 8, 1, 6, 34];
numbers.sort();
console.log(numbers);
The output of this code is as follows:
[1, 21, 34, 4, 6, 8]
By default, the sort method treats values as strings when comparing them.
This can lead to unexpected results when sorting numbers that have different lengths, like 1, 21, 34, 4, 6 and 8.
领英推荐
So, here comes The Power of Comparators!!!
To handle numeric values correctly, we can provide a custom comparator function
The comparator function takes two arguments, typically referred to as a and b, which represent two elements from the array. The comparator function should return a value that dictates the relative order of these two elements. Here's how the comparator function is structured:
function comparator(a, b) {
// Custom comparison logic goes here
// Return a negative value if a should come before b
// Return a positive value if a should come after b
// Return 0 if a and b are considered equal in terms of sorting }
Let's do the sorting using comparator method for the previous number array
const numbers = [4, 21, 8, 1, 6, 34];
number.sort(ascending);
function ascending(a,b){
return a-b;
}
console.log(numbers)
[1, 4, 6, 8, 21, 34]
const numbers = [4, 21, 8, 1, 6, 34];
number.sort(descending);
function descending(a,b){
return b-a;
}
console.log(numbers)
[34, 21, 8, 6, 4, 1]
Sorting array of objects
Arrays of objects can be sorted by comparing the value of one of their properties.
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
// sort by value
items.sort((a, b) => a.value - b.value);
// sort by name
items.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.nameA > b.name) {
return 1;
}
else{
return 0;
}
});
The comparator function (a, b) => {...} compares objects a and b based on their name property. Here's how it works:
In summary, comparators provide a flexible and powerful way to sort
Happy Coding!!