网站搜索

javascript - .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 类型将具有最高优先级,并且如果其 submitted_on 字段为空,将按到期日期从最早到最晚排序。如果有 submitted_on 条目,则应被推到最后。如果没有到期日期,则在到期日期中优先级最低。测试之后,所有其他类型将按到期日期从最早到最晚排序,并且那些有 submitted_on 字段的将始终具有最低优先级。

我的排序代码:

  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 中可行,我已经设法返回排序后的数组,但在 Firefox 中,它返回了错误的顺序。如何按照这个逻辑进行排序以在所有浏览器中都能工作?

答案#1

你没有对称的返回结果。

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; }