Sort is a built-in method of the array object. You can sort the elements in the array in ascending order. If no parameter is specified for the sort method, array elements are sorted by character encoding data. If you want to sort other types of elements, You need to implement a comparison function as a parameter to pass to sort. This function has two parameters a and B, if a is greater than B, return a number smaller than 0. If a is equal to B, return 0. Otherwise, return a value greater than 0.
Note that sorting is performed on the original array without generating copies.
For example, if an array is [20, 17, 15, 30, 100], the default sorting result is, 15, 30. We can see that it is not sorted by the value size. If you want to sort by the value size, you can implement a function by yourself, such:
The Code is as follows: |
Copy code |
Function intSort (a, B ){ Return a-B; } Var arr = [20, 17, 15, 30, 100]; Arr. sort (intSort ); // Or anonymous Functions Arr. sort ( Function (a, B ){ Return a-B; } ); |
// Sort in reverse order
Arr. sort (intSort). reverse (); in addition, if you want to sort in descending order, you can perform sort on the array and then call the reverse method.
Example
The Code is as follows: |
Copy code |
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <Html xmlns = "http://www.w3.org/1999/xhtml"> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Title> Javascript Array sorting </title> <Script type = "text/javascript"> S = [ {First: 'job', last: 'awk '}, {First: 'zwe', last: 'oli '}, {First: 'job', last: 'asp '} ]; For (var I = 0; I <s. length; I ++ ){ Document. write (s [I]. first + "+ s [I]. last +" <br/> "); } Document. write ("S. sort (function (a, B ){ Var result = a. first. localeCompare (B. first ); If (result = 0) Result = a. last. localeCompare (B. last ); Return result; }) For (var I = 0; I <s. length; I ++ ){ Document. write (s [I]. first + "+ s [I]. last +" <br/> "); } </Script> </Head> <Body> </Body> </Html> |