The sort () method is used to sort the elements of an array. Included in header file algorithm
Grammar
Arrayobject.sort (SortBy)
Parameters |
Description |
SortBy |
Optional. Specify the sort order. Must be a function. |
return value
The reference to the array. Note that the array is sorted on the original array and no replicas are generated.
First, the default situation
By default, the sort () method arranges the array items in ascending order. To implement sorting, the sort () method invokes the ToString () transformation method for each array item, and then compares the resulting string to determine how to sort. As follows:
var values = ["Orange", "apple", "banana"];
Values.sort ();
Console.log (values);/results ["apple", "banana", "orange"]
However, even if each item in the array is a numeric value, the sort () method compares the string as follows:
var values = [,,,,];
Values.sort ();
Console.log (values);/result [,,,,]
Second, the number of the order
The sort () method can receive a comparison function as an argument.
The comparison function receives two arguments, returns a negative number if the first argument should precede the second argument, and returns 0 if the two arguments are equal, and returns a positive number if the first argument is after the second.
function Compare (A, b) {return
(a-b);
} Comparison functions in ascending order
var values = [,,,,];
Values.sort (compare);
Console.log (values);/result [,,,,]
Sort the array according to an object attribute
First, you define a function that receives a property name and then creates a comparison function based on the property name. The following is the definition of this function:
function Createcomparisonfunction (PropertyName) {return
function (object, object) {
var a = object[ PropertyName];
var b = object[propertyname];
if (a < b) {return
-;
} else if (a > B) {return
;
} else{return;}}
Returns a comparison function in ascending order created based on the property name
After the internal function receives the PropertyName parameter, it uses the bracket notation to get the value of the given property.
The above function can be used like this in the following example.
var data = [{name: ' Lily ', Age:}, {name: ' Judy ', Age:}];
Data.sort (createcomparisonfunction ("name"));
Console.log (data[].name);//judy
Data.sort (createcomparisonfunction ("Age"))
; Console.log (data[].name);//lily
The above content is a small series to introduce the sort () function of a variety of uses, I hope that the above help!