sort () to sort an array

First, the default sort array

 was arr = [8,7,6,1,2,4,3,9,5 ]
 console.log(arr.sort())

Output Results: [1, 2, 3, 4, 5, 6, 7, 8, 9], the default is ascending, ascending

Two, Sort () function implemented in descending comparison, in descending order

    was arr = [8,7,6,1,2,4,3,9,5 ]
    console.log(arr.sort(function(a,b){
      return b- a
    }))

Output Results: [9, 8, 7, 6, 5, 4, 3, 2, 1]

Knowledge points:

1. The parameters a and B, is sequentially taken two successive elements from the array, such as the first two elements selected from 8.7 to examples.
Therefore, in the anonymous function  b - a result is -1.

Look at the relationship between the results with sorted anonymous function:
is less than  0 , then  a is arranged to  b advance;
if it is equal  0 ,  a and  b the relative position change. NOTE: The ECMAScript standard does not guarantee this behavior, but not all browsers will follow (for example, versions of Mozilla before 2003);
if more than  0 ,  b will be arranged to  a before.
It must always return the same result of the comparison to the same input, otherwise the sort of result will be uncertain.

Third, the Chinese implement sorting

    var Array = [ 'most', 'ah', 'pass', 'No' ];
     var resultArray = Array.sort (
       function (the param1, param2) {
         return param1.localeCompare (param2, "ZH" )
      }
    )
    console.log(resultArray)
    var resultArray2 = array.sort(
      function (param1, param2) {
        return param2.localeCompare(param1,"zh")
      }
    )
    console.log(resultArray2)

Output:

1. [ "ah", "no", "pass", "most"]

2. [ "most," "Biography", "no", "ah"]

Guess you like

Origin www.cnblogs.com/qiuchuanji/p/12083781.html