Several sorting an array of methods! ! !

The method of sorting a sort Dian

XX = the let [. 1,. 7,. 8,. 4,. 3] 
      xx.sort (function (A, B) { 
        // descending 
        return B - A 
     // ascending
     // return A- B
}) the console.log (XX)

Output below

Two Dian sort an array of objects based on an attribute

 1 let xx =[
 2     {name:"张三",age:18},
 3     {name:"李四",age:19},
 4     {name:"王五",age:20},
 5 ]
 6 let handle = (property)=>{
 7      return function(a,b) {
 8        let x1 = a[property]
 9        let x2 = b[property]
10        //降序
11       return x2 - x1  
12    }
13 }   
14 
15 xx.sort(handle('age'))
16 console.log(xx)

Output below

Wed and bubble sort

      // declare an array xx 
      the let xx = [. 7,. 5,. 6,. 1, 2,. 4,. 3,. 9,. 8 ]
       // Method paiXu xx passed as a parameter 
      function paiXu (xx) {
         // declare i and j, and temVal 
        I = the let xx.length 
        the let J 
        the let temVal 
        // when the length of the array is greater than zero xx 
        the while (I> 0 ) {
           for (J = 0; J <I -. 1; J ++ ) {
             iF (xx [J]> xx [+ J. 1 ]) {
               // the xx [j] assignment temVal 
              temVal = xx [j]
               // put xx [j + 1] assignment xx [j] 
              xx [j] = XX [J +. 1 ]
              // then temVal assignment xx [j + 1] 
              xx [j + 1] = temVal
               // This realizes xx [j] and the value xx [j + 1] is reversed 
            } 
          } 
          // I <= 0 when exit loop 
          i-- 
        } 
        // array sort function returns after xx 
        return xx 
      } 
      // array after receiving statements sort 
      the let newxx = paiXu (xx) 
      the console.log (newxx)

The output below it if necessary as long as the descending xx [j]> xx [j + 1] is larger than a number smaller than the number can be changed

 

Guess you like

Origin www.cnblogs.com/LiuRunMin/p/11877480.html