.sort不适用于firefox,但适用于chrome



我有一个对象数组,比如:

[
{"type":"TEST", "submitted_on":null, "due_date": new Date(xxx) },
{"type": "ESSAY", "submitted_on": new Date(xxx), "due_date":new Date(xxx)},
{"type": "TEST", "submitted_on":new Date(xxx), "due_date": new Date(xxx)},
{"type":"FILE", "submitted_on":new Date(xxx), "due_date":null}
]

我想按以下顺序排序:

TEST类型将具有最高优先级,并且如果其submited_on字段为空,则将按截止日期从早到晚的顺序排在第一位。如果它有一个submited_on条目,它应该被推到最后。如果没有截止日期,则在截止日期中具有最低优先级。测试后,所有其他类型将根据due_date从最早到最晚推送,并且那些在字段上提交的类型将始终具有最低优先级:

我的排序代码:

sortAssignments(assignments) {
const sortedArray = assignments.sort((n1, n2) => {
if (!n1.submitted_on && n2.submitted_on) {
return -1;
} else {
if (n1.type === "TEST" && n2.type !== "TEST" && !n1.submitted) {
return -1;
} else if (n1.due_date < n2.due_date) {
return -1;
} else {
return 1;
}
}
});
return sortedArray;
}

这个解决方案在firefox中有效,我已经设法按排序顺序返回了数组,但在firebox中,它返回的顺序不正确。如何在这种逻辑中进行排序,以便在所有浏览器上都能工作?

您没有对称的返回结果。

const data = [{ type: "TEST", submitted_on: null, due_date: new Date('2020-05-02') }, { type: "ESSAY", submitted_on: new Date('2020-05-02'), due_date: new Date('2020-0-502') }, { type: "TEST", submitted_on: new Date('2020-05-02'), due_date: new Date('2020-05-02') }, { type:"FILE", submitted_on: new Date('2020-05-02'), due_date: null }];
data.sort((a, b) =>
(b.type === 'TEST') - (a.type === 'TEST') ||
(b.submitted_on === null) - (a.submitted_on === null) ||
a.due_date - b.due_date
);
console.log(data)
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新