1.普通数组排序
var arr = [3,1,2,4,5,6,8,0,1];
//自定义排序规则
function compareTo(object1,object2){
if(object1 < object2){
return -1;
}else if(object1 > object2){
return 1;
}else{
return 0;
}
}
arr.sort(compareTo);
结果[0, 1, 1, 2, 3, 4, 5, 6, 8]
2:对象数组中,根据某一属性对数组对象排序
var arr = [{name:'张三',age:23},{name:'李四',age:24},{name:'王五',age:25}];
function createComparator(property){ return function (object1,object2){ var value1 = object1[property]; var value2 = object2[property]; if(value1 < value2 ){ return -1; }else if(value1> value2 ){ return 1; }else{ return 0; } } }
arr.sort(createComparator("name"));
结果:[
{name: "张三", age: 23},{name: "李四", age: 24},{name: "王五", age: 25}]
Best Regards