在本教程中,学习如何以多种方式对数字、字符串和对象的数组进行排序。
让我们来声明日期数组
var arrayJson = [
'2011-01-01 02:00:00',
'2019-01-01 02:00:00',
'2001-01-01 02:00:00',
'2021-01-01 02:00:00',
'2020-01-01 02:00:00',
'2020-02-01 02:00:00',
'1990-01-01 02:00:00'
];
数组的sort()方法默认以升序对数组进行排序。它使用一个回调比较器来编写一个自定义逻辑。
array.sort()方法将数组以升序排序。
let result = arrayJson.sort(function(a, b) {
return new Date(a).getTime() - new Date(b).getTime();
});
console.log(result)
而输出的结果是
[ '1990-01-01 02:00:00', '2001-01-01 02:00:00', '2011-01-01 02:00:00', '2019-01-01 02:00:00', '2020-01-01 02:00:00', '2020-02-01 02:00:00', '2021-01-01 02:00:00']
如果你想要一个相反顺序的日期数组,即降序。你必须使用一个排序比较器。让我们以相反的顺序对数字进行排序,即降序。
let result = arrayJson.sort(function(a, b) {
return new Date(b).getTime() - new Date(a).getTime();
});
console.log(result)
而输出结果是
[ '2021-01-01 02:00:00', '2020-02-01 02:00:00', '2020-01-01 02:00:00', '2019-01-01 02:00:00', '2011-01-01 02:00:00', '2001-01-01 02:00:00', '1990-01-01 02:00:00']
上面的例子使用ES5代码数组排序回调。
使用ES6,可以使用数组函数写一个回调比较器
使用ES6(ECMAScript2015),同样可以使用箭头函数重写如下
对数组进行升序排序的代码是
let result = arrayJson.sort((a,b)=> new Date(a).getTime() -
new Date(b).getTime());
用以下方式对日期数组进行降序排序
let result = arrayJson.sort((a,b)=> new Date(b).getTime() -
new Date(a).getTime());
让我们以这个为例
[
{
id: 1,
name: "john",
lastModified: '2011-01-01 02:00:00'
},
{
id: 2,
name: "Franc",
lastModified: '2001-01-01 02:00:00'
},
{
id: 3,
name: "Andrew",
lastModified: '2021-01-01 02:00:00'
},
{
id: 11,
name: "Mark",
lastModified: '2020-01-01 02:00:00'
},
{
id: 12,
name: "Eric",
lastModified: '2020-02-01 02:00:00'
},
{
id: 8,
name: "Tony",
lastModified: '1990-01-01 02:00:00'
}
]
下面是用日期键对JSON数组进行升序排序的代码
let result = arrayJson.sort((a,b)=> new Date(a.lastModified).getTime() -
new Date(b.lastModified).getTime());
console.log(result)
降序排序
let result = arrayJson.sort((a,b)=> new Date(b.lastModified).getTime() -
new Date(a.lastModified).getTime());
console.log(result)
总结
在这篇文章中,你学到了如何对以下不同类型的数组进行排序。
- 用ES6和ES5对日期数组进行升序或降序排序
- 对象数组json的关键日期排序
我希望你通过这篇文章学到了新的东西。