definition and Usage:
The sort () method is used to sort elements of an array.
Grammar:
Arrayobject.sort (SortBy)
Note: sortby, optional, specifies the sort order, which must be a function.
Description:
If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded .
To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
Chestnuts:
The sort () method completes the task satisfactorily when applied to a scene of a single digit or letter as shown above;
However, an exception occurred while processing the array shown in the following pest:
The numbers are not arranged in the order of the values from small to large, but in the order of the size of the characters encoded;
Workaround:
Provides a sort function that compares 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, a value that is less than 0 is returned if a should appear before B in the sorted array.
- If a equals B, 0 is returned.
- If a is greater than B, a value greater than 0 is returned.
As you can see: The following comparison function allows the array to be sorted from small to large
function (A, a) {return a-B;}
Similarly: The following comparison function allows you to sort the array from large to small
function (A, b) {return b-a;}
Other application examples:
Javascript:sort () method for fast array sorting