Introduction to the use of javascript array sort functions sort and reverse

  • 2020-03-29 23:56:15
  • OfStack

First let's talk about the reverse method.

The reverse method reverses the position of elements in an Array object. This method does not create a new Array object during execution.

Such as:
 
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 contains only Numbers, the Numbers are sorted in descending order, and if there are other types in the array, the array is reversed and returned.

Sort method

Returns an Array object whose elements have been sorted.
 
arrayobj.sort(sortfunction) 

parameter

arrayObj

Will be options. 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 are arranged in ascending ASCII character order.

The sort method sorts the Array objects appropriately; No new Array object is created during execution.

If a function is provided for the sortfunction parameter, the function must return one of the following values:

Negative value if the first parameter passed is smaller than the second parameter.
Zero if the two parameters are equal.
Positive value, if the first parameter is bigger 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 array.
alert(l); //Returns the sorted array.

In this example, there is no comparison function passed in so the elements will be sorted in ASCII character order in ascending order. In addition, this array contains many types of data, so even if the comparison function is passed in, it will still be sorted in ASCII character order in ascending order.

For example,
 
var a, l; //Declare variables.
a = ["X" ,"y" ,"d", "Z", "v","m","r",false,0]; 
l = a.sort(); //Sort array.
alert(l); //Returns the sorted array.
ll = a.sort(compack); 
alert(ll);//Returns the same as above
function compack(a,b){ 
return a-b; 
} 

We can use the sort method when we need to sort Numbers, just pass it a comparison function to make it easy to sort up and down.

Ascending order:
 
var a, l; //Declare variables.
a = [6,8,9,5.6,12,17,90]; 
l = a.sort(compack); //Sort array.
alert(l); //Returns 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); //Returns the sorted array.

function compack(a,b){ 
return b-a; 
} 

In the comparison function the ascending returns a minus b and the descending returns b minus a.

Related articles: