首页 > 解决方案 > JavaScript中的日期和数字混合排序

问题描述

我想按三个值对这个 JavaScript 数组进行排序,但我似乎无法弄清楚如何一次按多个属性进行排序。

要求是:

  1. 按 createdAt 降序排列
  2. 按状态降序排列
  3. 按升序排列

这是数组:

var items [
    { status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
    { status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
];

结果应该是:

var items [
    { status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
    { status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
    { status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
];

我试过了。

test.sort((a, b) => 
      new Date(b[type].createdAt) - new Date(a[type].createdAt) 
      || b[type].status - a[type].status 
      || Date.parse(a[type].end) - Date.parse(a[type].end));

它失败了......

标签: javascriptarrayssorting

解决方案


您可以为多个排序条件设置 OR 条件:

items.sort((a,b)=>{
    return new Date(b.createdAt)-new Date(a.createdAt) || b.status-a.status || new Date(a.end)-new Date(b.end)
})

推荐阅读