轉載自: blog.csdn.net/weixin_4119…
1. 普通数组排序
1.1 升序(从小到大)
var arr3 = [30,10,111,35,1899,50,45];
arr3.sort(function(a,b){
return a - b;
})
console.log(arr3);//输出 [10, 30, 35, 45, 50, 111, 1899]
1.2 降序(从大到小)
var arr4 = [30,10,111,35,1899,50,45];
arr4.sort(function(a,b){
return b - a;
})
console.log(arr4);//输出 [1899, 111, 50, 45, 35, 30, 10]
1.3 获取最大值
function getMax(arr) {
if (arr != null && (arr instanceof Array) && arr.length > 0) {
let arr2 = arr.concat([]);
arr2.sort(function (a, b) { return a - b })
let max = arr2[arr2.length - 1];
return max;
}
return null;
}
var arr7 = [30,10,111,35,1899,50,45];
let max = getMax(arr7)
console.log(max); //得到 1899
2. 对象数组排序
2.1 按id属性升序排列
var arr5 = [{id:10},{id:5},{id:6},{id:9},{id:2},{id:3}];
arr5.sort(sortBy('id',1))
//attr:根据该属性排序;rev:升序1或降序-1,不填则默认为1
function sortBy(attr,rev){
if( rev==undefined ){ rev=1 }else{ (rev)?1:-1; }
return function (a,b){
a=a[attr];
b=b[attr];
if(a<b){ return rev*-1}
if(a>b){ return rev* 1 }
return 0;
}
}
console.log(arr5);
//输出新的排序
// {id: 2}
// {id: 3}
// {id: 5}
// {id: 6}
// {id: 9}
// {id: 10}
2.2 获取最大值——对象数组中的指定属性
function getObjArrMax(arr, prop) {
if (arr != null && (arr instanceof Array) && arr.length > 0) {
let arr2 = arr.concat([]);
arr2.sort(function (a, b) { return a[prop] - b[prop] })
let max = arr2[arr2.length - 1][prop];
return max;
}
return null;
}
let arr8 = [{id:10},{id:5},{id:6},{id:9},{id:2},{id:3}];
let max = getObjArrMax(arr8,'id')
console.log(max); //得到10
2.3 对象数组排序——多属性
先根据id升序,id相同的根据age降序
var arr6 = [{id:10,age:2},{id:5,age:4},{id:6,age:10},{id:9,age:6},{id:2,age:8},{id:10,age:9}];
arr6.sort(function(a,b){
if(a.id === b.id){//如果id相同,按照age的降序
return b.age - a.age
}else{
return a.id - b.id
}
})
console.log(arr6);
//输出新的排序
// {id: 2, age: 8}
// {id: 5, age: 4}
// {id: 6, age: 10}
// {id: 9, age: 6}
// {id: 10, age: 9}
// {id: 10, age: 2}
2.4 萬能公式
// 排序顺序:today status doDate doTime
this.data.sort(function(a, b) {
if (a.today === b.today) {
if (a.status === b.status) {
if (a.doDate === b.doDate) {
// 时间字符串转换为时间进行比较
return (new Date(a.doDate + ' ' + a.doTime)) - (new Date(b.doDate + ' ' + b
.doTime))
} else {
// 当 doDate 为空时
if (!a.doDate && !b.doDate) {
return 0
} else if (!a.doDate) {
return -1
} else if (!b.doDate) {
return 1
} else {
// 时间字符串转换为时间进行比较
return (new Date(a.doDate)) - (new Date(b.doDate))
}
}
} else {
return a.status - b.status
}
} else {
return b.today - a.today
}
})