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:
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:
I hope this article will be helpful to everyone’s JavaScript programming design.