This article describes how js uses Array.prototype.sort() to sort array objects. Share it for your reference. The specific analysis is as follows:
When talking about sorting array objects, let's first briefly understand Array.prototype.sort(). The sort method accepts a parameter - Function. The function will provide two parameters, respectively, two elements that are compared. If the element is String, it will be compared through Unicode code. If it is Number, the size of the value is compared. If 1 is returned in the function compared, two elements will be exchanged, and 0 and -1 will not be exchanged. Let’s take a look at an example:
The code copy is as follows: var arr = [3, 5, 2, 1];
//Sorting from small to large
arr.sort(function (a, b) {
return a > b ? 1 : -1;
});
// The result is: [1, 2, 3, 5]
So back to our topic, how should I write it if I sort an array object? In fact, the principle is the same as above, such as:
Copy the code as follows: var arr = [
{ a : 2, b : 3.2},
{ a : 3, b : 1.2},
{ a : 4, b : 2.2},
{ a : 6, b : 1.2},
{ a : 5, b : 3.2}
]
///Sorted by attribute b from small to large
arr.sort(function(x, y){
return xb > yb ? 1:-1;
});
x and y are an element of arr, that is, an object, so you can directly compare the properties of the two objects.
In the above example, there are duplications in the smallest element. If the requirement is: first sort from small to large according to the b attribute, and if there are duplications in the smallest, then sort by the a attribute, how should I write it?
When sorting, first sort by b attribute. If xb is greater than yb, move x to the right of y. If xb is equal to yb, then compare it with xa and ya. Therefore, the code is as follows:
Copy the code as follows: arr.sort(function (x, y) {
if (xb > yb) {
return 1;
} else if (xb === yb) {
return xa > ya ? 1 : -1;
} else if (xb < yb) {
return -1;
}
})
I hope this article will be helpful to everyone's JavaScript programming.