javascript - JavaScript中的日期和数字混合排序
问题描述
我想按三个值对这个 JavaScript 数组进行排序,但我似乎无法弄清楚如何一次按多个属性进行排序。
要求是:
- 按 createdAt 降序排列
- 按状态降序排列
- 按升序排列
这是数组:
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));
它失败了......
解决方案
您可以为多个排序条件设置 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)
})
推荐阅读
- python-3.x - 按分隔符将列表拆分为子列表
- visual-studio - 在 TFS 中签入时从 Visual Studio 中恢复已删除的文件/代码
- php - 警告:file_exists() 期望参数 1 是有效路径,数组在 C:\
- mediawiki - 条件类别
- javascript - 如何使用 ASP.NET 从 MSSQL 中获取 JQuery 自动完成小部件的数据
- java - 为什么此 java 代码无法将图像保存在 mysql 数据库中?
- java - 错误:无法找到或加载主类 cucumber.cli.Main
- javascript - Typescript:比较作为接口类型的对象是否等于另一个对象具有相同的接口类型
- javascript - 如何使用 Angular 6 中的组件交互使用事件将文本替换为文本框
- javascript - 如何为特定目的正确使用点击功能