First, let’s talk about the reverse method.
The reverse method reverses the position of elements in an Array object. During execution, this method does not create a new Array object.
For example:
var array1 = [ 'a','cc','bb','hello',false,0,3];
var array2 = [3,5,2,1,7,9,10,13];
array1.reverse();
array2.reverse();
alert(array1);
alert(array2);
If the array only contains numbers, then the numbers will Sort in descending order. If the array contains other types, reverse the array and return the array.
sort method
Returns an Array object whose elements have been sorted.
arrayobj.sort(sortfunction)
Parameters
arrayObj
Required. Any Array object.
sortFunction
Optional. is the name of the function used to determine the order of elements. If this parameter is omitted, the elements will be sorted in ascending ASCII character order. The
sort method sorts Array objects appropriately; no new Array objects are created during execution.
If a function is provided for the sortfunction argument, the function must return one of the following values:
A negative value if the first argument passed is smaller than the second argument.
Zero if both arguments are equal.
Positive value if the first parameter is larger than the second parameter.
Example 1: ()
var a, l; // Declare variables.
a = ["X" ,"y" ,"d", "Z", "v","m","r",false,0];
l = a.sort(); // Sort the array.
alert(l); // Return the sorted array.
In this example, if the comparison function is not passed in, the elements will be arranged in ascending order according to ASCII character order. In addition, this array contains multiple types of data, so even if the comparison function is passed in, it will still Arrange in ascending order according to ASCII character order.
For example
var a, l; // Declare variables.
a = ["X" ,"y" ,"d", "Z", "v","m","r",false,0];
l = a.sort(); // Sort the array.
alert(l); // Return the sorted array.
ll = a.sort(compack);
alert(ll);//The return is the same as above
function compack(a,b){
return a-b;
}
When we need to sort numbers, we can use the sort method. As long as we pass a comparison function to it, we can easily ascend and descend.
Ascending order:
var a, l ; // Declare variables.
a = [6,8,9,5.6,12,17,90];
l = a.sort(compack); // Sort array.
alert(l); // Return the sorted array.
function compack(a,b){
return a-b;
}
Descending order:
var a, l; // Declare variables.
a = [6,8,9,5.6,12,17,90];
l = a.sort(compack); // Sort array.
alert(l); // Return the sorted array.
function compack(a,b){
return b-a;
}
In the comparison function, return a-b in ascending order and b-a in descending order.