The sort () method is used to sort the elements of an array and to return arrays. The default sort order is based on the string Unicode code. Because sorting is sorted in the order of the string Unicode codes, the array elements should first be converted to strings (if necessary) for comparison.
Syntax: Arrayobject.sort (sortby);
The parameter sortby is optional and is used to specify the order of sorts, but it must be a function.
Example one: Sort by alphabetical order
Example two: or Sort by letter
Nani, this sort of doesn't seem to get the results you want ...
If you want to get the results you want, either ascending or descending, you need to provide a comparison function. The function compares the size of two values and returns a number that describes the relative order of the two values.
The comparison function should have two parameters A and B with the following return values:
If a is less than B, that is, a-a is less than 0, a value less than 0 is returned, and the array is sorted in ascending order.
If a equals B, 0 is returned.
If a is greater than B, that is, a-a is greater than 0, a value greater than 0 is returned, and the array is sorted in descending order.
Example three: ascending order
Example four: Descending sort
What if you want to sort by a property value in an Array object???
Example five: Sort by an attribute value in an array object
Example six: Depending on the parameter to determine whether ascending or descending
Reprint: https://www.cnblogs.com/saifei/p/9043821.html
The principle and use of the sort () method in JS