以下是TypeScript中的动态数组,我希望按激活日期降序排序。
notificationList = [];
notificationList = [ {"Id:11", "ActivationDate":"29-Jan-2018"},
{"Id:21", "ActivationDate":"22-Jan-2018"},
{"Id:8", "ActivationDate":"01-Feb-2018"},
{"Id:10", "ActivationDate":"25-Jan-2018"},
{"Id:12", "ActivationDate":"24-Jan-2018"},
{"Id:05", "ActivationDate":"28-Jan-2018"},
{"Id:04", "ActivationDate":"24-Jan-2018"},
]
我正在使用下面的代码进行排序,但它没有给我预期的输出。
this.notificationList = this.notificationList.sort(function(a, b): any {
const dateA = new Date(a['ActivationDate']);
const dateB = new Date(b['ActivationDate']);
console.log('dateA -' + dateA);
console.log('dateB -' + dateB);
console.log(dateB > dateA);
return dateB > dateA; //sort by date decending
});
有任何建议或意见吗?
答案 0 :(得分:1)
要排序的回调应该return a number:
let notificationList = [
{ "Id": 11, "ActivationDate": "29 Jan 2018" },
{ "Id": 21, "ActivationDate": "22 Jan 2018" },
{ "Id": 8, "ActivationDate": "01 Feb 2018" },
{ "Id": 10, "ActivationDate": "25 Jan 2018" },
{ "Id": 12, "ActivationDate": "24 Jan 2018" },
{ "Id": 5, "ActivationDate": "28 Jan 2018" },
{ "Id": 4, "ActivationDate": "24 Jan 2018" },
];
notificationList = notificationList.sort(function (a, b): any {
const dateA = new Date(a['ActivationDate']);
const dateB = new Date(b['ActivationDate']);
return dateB > dateA ? 1 : dateB < dateA ? -1 : 0; //sort by date decending
});
注意您使用的日期格式为not officially supported,仅适用于Chrome。我从日期中删除了-
,将日期转换为支持的格式。
答案 1 :(得分:0)
您的比较是错误的,您应该使用<
代替<
this.notificationList.sort((a, b)=> {
let dateA = new Date(a['ActivationDate']);
let dateB = new Date(b['ActivationDate']);
return dateA < dateB; // sort by descending
});
<强> LIVE DEMO 强>