按创建时间日期排序
例如 eg
1.升序
2.降序
返回的结果:
注: 支持IE和Chrome其他的浏览器可自行测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let arr = [
{ time: '2020-4-5' },
{ time: '2020-4-2' },
{ time: '2020-4-22' },
{ time: '2020-1-5' },
{ time: '2020-2-5' },
{ time: '2020-3-5' },
]
//倒序
arr.sort(function (a, b) {
return a.time < b.time ? 1 : -1;
})
//正序
arr.sort(function (a, b) {
return a.time > b.time ? 1 : -1;
})
console.log(arr);
</script>
</body>
</html>
let data = [
{
count:"8",
name: "21-09"
},{
count:"8",
name: "20-11"
},{
count:"8",
name: "20-12"
},{
count:"8",
name: "21-01"
}
]
data.sort(function (a,b){
return a.name > b.name ? 1 : -1 //升序 < 降序
})
console.log(data); //(4) [{…}, {…}, {…}, {…}]
0: {count: '8', name: '20-11'}
1: {count: '8', name: '20-12'}
2: {count: '8', name: '21-01'}
3: {count: '8', name: '21-09'}
length: 4
[[Prototype]]: Array(0)
近期写项目,需要用对象的中一个key来进行排序,发现element框架表格带的排序不太好用,于是自己封装了一个函数,来根据日期进行排序,也可以根据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'
}
]
function dateData(property, bol) { //property是你需要排序传入的key,bol为true时是升序,false为降序
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类型排序
function compare(property, bol) {//property是你需要排序传入的key,bol为true时是升序,false为降序
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)))
如果对你有帮助,记得点赞哦,欢迎指导,如果哪有需要改进的,或者哪里有看不懂的,评论区里留言,我会第一时间回复,每天一更,,,,,
按创建时间日期排序
例如 eg
1.升序
2.降序
返回的结果:
注: 支持IE和Chrome其他的浏览器可自行测试
转载于:https://www.cnblogs.com/gaoht/p/9982898.html