JavaScript中用sort方法进行二维数组排序

JavaScript中数组排序方法

用到的最多的当然是封装好的sort()方法了 一:sort()方法怎么使用? sort方法并不像我们想的那么容易使用,不是单纯的arr.sort()就行了,需要我们定义里面的回调函数!因为sort()方法默认情况下按照升序排列数组项,sort()方法会调用toString()转型方法,然后比较得到的字符串,即使我们比较的是数字,他也会把数字转为字符串以后再排序。 请看下面例子:

var arr1 = [0, 1, 3, 10, 16, 5, 9, 0, 3];
var arr2 = [bangbang, father, mother, brother, sister, true, false, 0, 1, 6, 13];
console.log(arr1.sort()) //很明显,这样不是我们要的结果,[ 0, 0, 1, 10, 16, 3, 3, 5, 9 ]
console.log(arr2.sort()); //[ 0,1,13,6,bangbang,brother,false,father,mother,sister,true]

//传入自定义回调函数之后
function ascend(a,b){
    return a-b;
}
//降序排列
function descend(a,b){
    return b-a;
}
console.log(arr1.sort(ascend));     //[ 0, 0, 1, 10, 16, 3, 3, 5, 9 ]
console.log(arr1.sort(descend));    //[ 16, 10, 9, 5, 3, 3, 1, 0, 0 ]
 
        
 1
         
  2
         
  3
         
  4
         
  5
         
  6
         
  7
         
  8
         
  9
         
  10
         
  11
         
  12
         
  13
         
  14
         
  15

二:用sort方法进行二维数组的排序。

var arr1 = [[4,5,7],[11,3,6,100,77],[12,9,12,10],[3,1,2,99,22]];
function ascend(x,y){
    return x[3] - y[3];  //按照数组的第4个值升序排列
}
function descend(x,y){
    return y[0] - x[0];  //按照数组的第1个值升序排列
}
console.log(arr1.sort(ascend));
console.log(arr1.sort(descend));
 
        
 1
         
  2
         
  3
         
  4
         
  5
         
  6
         
  7
         
  8
         
  9

当然还有其他的排序方法,再次我只说封装好的,其实排序有很多种,关键看你怎么使用! 三:顺便什么是reverse()方法?怎么使用? reverse方法会反转数组项的顺序,请看如下示例:

var arr1 = [0, 1, 3, 10, 16, 5, 9, 0, 3];
var arr2 = [bangbang, father, mother, brother, sister, true, false, 0, 1, 6, 13];
console.log(arr1.reverse());//[ 3, 0, 9, 5, 16, 10, 3, 1, 0 ]
console.log(arr2.reverse());//[ 13,6,1,0,false,true,sister,brother,mother,father,bangbang ]
经验分享 程序员 微信小程序 职场和发展