這是使用無窮大對資料進行排序的正確方法嗎?嘗試了解決方案,但這不是我所需要的。
data = [{
"status": "Accepted",
"endTime": ""
}, {
"status": "New",
"endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
"status": "In Progress",
"endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
"status": "Accepted",
"endTime": "Sep 16 2022, 04:19 GMT 5"
}, {
"status": "Kick Off Policy Review Task",
"endTime": "Sep 16 2022, 04:13 GMT 5"
}];
// sort based on this order
sortDSCOrder = [
'Canceled',
'Accepted',
'Completed',
'On-Hold',
'In Progress',
'Not Started',
'New',
'Kick Off General Query Task',
'Kick Off Policy Review Task',
];
描述排序:
data.sort((a, b) => {
return (
(b.endTime ? new Date(b.endTime).getTime() : Infinity) -
(a.endTime ? new Date(a.endTime).getTime() : Infinity) ||
this.sortDSCOrder.indexOf(a.status) -
this.sortDSCOrder.indexOf(b.status)
);
});
ouptput = [{
"status": "Accepted",
"endTime": ""
}, {
"status": "Accepted",
"endTime": "Sep 16 2022, 04:19 GMT 5"
}, {
"status": "In Progress",
"endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
"status": "New",
"endTime": "Sep 16 2022, 04:18 GMT 5"
}, {
"status": "Kick Off Policy Review Task",
"endTime": "Sep 16 2022, 04:13 GMT 5"
}];
uj5u.com熱心網友回復:
問題是因為您用于將值轉換為日期的邏輯存在缺陷。1由于轉換為 Date 物件時的型別強制,當您回傳或-1在比較之后而不是減去它們的值時,日期將移到頂部。以這種方式進行比較意味著您不需要強制空值/空值Infinity讓它們首先出現。
const sortDSCOrder = ["Canceled","Accepted","Completed","On-Hold","In Progress","Not Started","New","Kick Off General Query Task","Kick Off Policy Review Task",];
const data = [{status:"Accepted",endTime:""},{status:"New",endTime:"Sep 16 2022, 04:18 GMT 5"},{status:"In Progress",endTime:"Sep 16 2022, 04:18 GMT 5"},{status:"Accepted",endTime:"Sep 16 2022, 04:19 GMT 5"},{status:"Kick Off Policy Review Task",endTime:"Sep 16 2022, 04:13 GMT 5"}];
data.sort((a, b) => {
const aDate = new Date(a.endTime);
const bDate = new Date(b.endTime);
const aStateIndex = sortDSCOrder.indexOf(a.status);
const bStateIndex = sortDSCOrder.indexOf(b.status);
return aDate < bDate ? 1 : aDate > bDate ? -1 : aStateIndex - bStateIndex;
});
console.log(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514780.html
