根据日期进行排序,也可以根据number类型的大小来进行排序
- 按日期排序的函数
let data = [
{
id: 2,
time: '2019-04-26 10:53:19'
},
{
id: 4,
time: '2019-04-26 10:51:19'
},
{
id: 1,
time: '2019-04-26 11:04:32'
},
{
id: 3,
time: '2019-04-26 11:05:32'
}
]
//property是你需要排序传入的key,bol为true时是升序,false为降序
function dateData(property, bol) {
return function(a, b) {
var value1 = a[property];
var value2 = b[property];
if (bol) {
// 升序
return Date.parse(value1) - Date.parse(value2);
} else {
// 降序
return Date.parse(value2) - Date.parse(value1)
}
}
}
console.log(data.sort(dateData("time", true)))
console.log(data.sort(dateData("time", false)))
- 非日期类型的number类型排序
//property是你需要排序传入的key,bol为true时是升序,false为降序
function compare(property, bol) {
return function(a, b) {
var value1 = a[property];
var value2 = b[property];
if (bol) {
// 升序
return value1 - value2;
} else {
// 降序
return value2 - value1;
}
}
}
console.log(data.sort(dateData("id", true)))
console.log(datas.sort(dateData("id", false)))