Definition and Usage
The sort () method is used to sort elements of an array.
Grammar
arrayobject. Sort (sortby)
Parameter sortby: Optional. Specifies the sort order. Must be a function.
return value
A reference to an array. Note that the array is sorted on the original array, and no replicas are generated.
normal array Ordering:
JS uses the method sort () to sort the array. The sort () method has an optional parameter, which is the function used to determine the order of the elements. If this argument is omitted, then the elements in the array will be sorted in ASCII character order . Such as:
The ASCII values of the letters A and B are 65, 66 respectively, and the values of A and B are 97 and 98 respectively, so the result of the above output is ["A", "B", "A", "B"]
If an array element is a number, it is also sorted by sort () to see how the effect looks:
There is no effect (sort by size), in fact, the sort method calls the ToString () method of each array item, gets the string, and then sorts the resulting string. Although the value is 15:3 large, "15" is preceded by "3" (ASCII character order) when a string comparison is made. Obviously, the result is not what we want, and then the parameter of the sort () method plays a role, and we call this parameter a comparison function.
The comparison function receives two parameters, returns a negative number if the first argument should precede the second, and returns 0 if the two arguments are equal, or returns a positive number if the first argument should be in the second one.
Array Object ordering:
An array item is an object that needs to be sorted against an array of an attribute of an item of the list. Actually, it's similar to the previous comparison function.
Here is an example of my project:
Now I want to sort the px field size, I do this:
Sorting array objects in JS (method sort () details)