const days = [
'2019-07-01', '2019-07-02',
'2019-07-03', '2019-07-04',
'2019-07-05', '2019-07-08',
'2019-07-09', '2019-07-10',
'2019-07-11', '2019-07-12',
'2019-07-15', '2019-07-17',
'2019-07-18', '2019-07-19',
'2019-07-23', '2019-07-24'
]
我有这个 Strings 数组。这些实际上是日期。有没有一种方法可以同时对此日期字符串进行升序和降序排序。 我尝试了这些,但似乎没有任何效果。
days.sort()
points.sort(function(a, b){return a - b})
如何使用JS实现此目标?
任何帮助! 非常感谢。
答案 0 :(得分:2)
升序:
days.sort();
降序:
days.sort().reverse();
答案 1 :(得分:1)
您可以通过将它们转换为日期并对它们进行比较来进行排序,并假定它们为 YYYY-MM-DD 格式:
const days = [
'2019-07-01', '2019-07-02',
'2019-07-03', '2019-07-04',
'2019-07-05', '2019-07-08',
'2019-07-09', '2019-07-10',
'2019-07-11', '2019-07-12',
'2019-07-15', '2019-07-17',
'2019-07-18', '2019-07-19',
'2019-07-23', '2019-07-24'
];
console.log(days.sort((a, b) => new Date(a) - new Date(b))); //asc
console.log(days.sort((a, b) => new Date(b) - new Date(a))); //desc
const days = [
'2019-07-01', '2019-07-02',
'2019-07-03', '2019-07-04',
'2019-07-05', '2019-07-08',
'2019-07-09', '2019-07-10',
'2019-07-11', '2019-07-12',
'2019-07-15', '2019-07-17',
'2019-07-18', '2019-07-19',
'2019-07-23', '2019-07-24'
];
console.log(days.sort((a, b) => {
var d1 = a.split('-'),
d2 = b.split('-');
return new Date(d1[0], d1[1] - 1, d1[2]) - new Date(d2[0], d2[1] - 1, d2[2]);
//--------------^Year--^Month-----^day
}));
console.log(days.sort((a, b) => {
var d1 = a.split('-'),
d2 = b.split('-');
return new Date(d2[0], d2[1] - 1, d2[2]) - new Date(d1[0], d1[1] - 1, d1[2]);
}));
答案 2 :(得分:0)
在这里,我们有两个功能可以对日期进行升序和降序排序。
var date_sort_asc = function (date1, date2) {
if (new Date(date1) > new Date(date2)) return 1;
if (new Date(date1) < new Date(date2)) return -1;
return 0;
};
var date_sort_desc = function (date1, date2) {
if (new Date(date1) > new Date(date2)) return -1;
if (new Date(date1) < new Date(date2)) return 1;
return 0;
};
现在,您可以通过在sort函数(例如-
)中以回调的形式调用这些函数来对它们进行排序days.sort(date_sort_asc);
days.sort(date_sort_desc);