一般我们给一维数组排序,直接用arr.sort()方法就可以了:
function numAscSort(a, b) {
return a - b;
}
function numDescSort(a, b) {
return b - a;
}
有需求是给数组的某个属性排序,用以下方法就可以实现了:
function compareAscSort(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value1 - value2;
}
}
function compareDescSort(property){
return function(a,b){
var value1 = a[property];
var value2 = b[property];
return value2 - value1;
}
}
使用示例:
arr=[ //排序的数组
{name:'xx',age:12},
{name:'as',age:13},
{name:'sd',age:8}
];
asc_sort = arr.sort(compareAscSort("age"));
//排序之后的数组
asc_sort=[
{name: "sd", age: 8},
{name: "xx", age: 12},
{name: "as", age: 13}
]