数组对象排序
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (obj1, obj2) {
var val1 = obj1.name;
var val2 = obj2.name;
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
console.log(arr.sort(compare));
//输出结果为 [Object { name="wlz", age=25}, Object { name="zlw", age=24}]
上面的代码优化
//这个只能排序age属性值为number类型的,
//如果属性值为数值类型的就会有问题
//问题:只会比较第一位数字大小
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
arr.sort(compare("age"))//按照 age 进行排序
数组对象排序(没有问题)
var arr = [{name: "zlw", age: 24}, {name: "wlz", age: 25}];
var compare = function (prop) {
return function (obj1, obj2) {
var val1 = obj1[prop];
var val2 = obj2[prop];
if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
val1 = Number(val1);
val2 = Number(val2);
}
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
}
arr.sort(compare("age"))
数组排序sort
-
var arr = new Array('1','3','8','55','2','3','5','66'); function compare(a, b) { return b - a; } arr = arr.sort(compare); console.log(arr.toString())
- 简写
arr.sort( (a,b) => a - b )
排序arr.sort( (a,b) => b - a )
倒序
数组对象排序(用sort)
-
原理
-
第一种
var arr = [ {name:"zhangsan", age: 21,id:3}, {name:"lisi", age: 23,id:2}, {name:"wangwu", age: 20,id:1}, {name:"zhaoliu", age: 18,id:4}, {name:"xiaoming", age: 17,id:6}, {name:"xiaolan", age: 25,id:5} ] function compare() { return function(a, b) { return a['id'] - b['id']; } } arr = arr.sort(compare());
-
第二种
var arr = [ {name:"zhangsan", age: 21,id:3}, {name:"lisi", age: 23,id:2}, {name:"wangwu", age: 20,id:1}, {name:"zhaoliu", age: 18,id:4}, {name:"xiaoming", age: 17,id:6}, {name:"xiaolan", age: 25,id:5} ] function compare(arg) { return function(a, b) { return a[arg] - b[arg]; } } arr = arr.sort(compare('id'));
-
简写方式(项目中使用最方便)
arr = arr.sort((() => (a,b)=> a['id'] - b['id'])());