Home > Web Front-end > JS Tutorial > body text

js uses Array.prototype.sort() method to sort array objects_javascript skills

WBOY
Release: 2016-05-16 16:17:32
Original
1335 people have browsed it

The example in this article describes how js uses Array.prototype.sort() to sort array objects. Share it with everyone for your reference. The specific analysis is as follows:

When talking about sorting array objects, let’s first take a brief look at Array.prototype.sort(). The sort method accepts one parameter - Function. The function will provide two parameters, which are two elements to be compared. If the element is of type String, it will be compared through Unicode code. If it is of type Number, the size of the value will be compared. If the comparison function returns 1, the two elements exchange positions. 0 and -1 do not exchange positions. Let’s look at an example first:

Copy code The code is as follows:
var arr = [3, 5, 2, 1];
// Sort from small to large
arr.sort(function (a, b) {
Return a > b ? 1 : -1;
});
// Result obtained: [1, 2, 3, 5]

So back to our topic, if we are sorting an array object, how should we write it? In fact, the principle is the same as above, such as:

Copy code The code is 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}
]
/// Sort by attribute b from small to large
arr.sort(function(x, y){
Return x.b > y.b ? 1:-1;
});

x and y are an element of arr, that is, an object, so just compare the properties of the two objects directly.

In the above example, there are duplicates in the smallest element. If the requirement is: first sort by the b attribute from small to large, and if there are duplicates in the smallest element, then sort by the a attribute. How should I write it?

When sorting, first sort by the b attribute. If x.b is greater than y.b, move x to the right of y. If x.b is equal to y.b, compare x.a and y.a, so the code is as follows:

Copy code The code is as follows:
arr.sort(function (x, y) {
If (x.b > y.b) {
Return 1;
} else if (x.b === y.b) {
          return x.a > y.a ? 1 : -1;
} else if (x.b < y.b) {
         return -1;
}
})

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!