JavaScript数组多条件排序求助:日期与数字混合排序问题
解决JavaScript数组多属性排序问题
我来帮你搞定这个多属性排序的问题!你之前尝试的代码里有几个小疏漏,导致没实现预期的排序效果,咱们来一步步修正:
先说说你代码里的问题
- 错误引用了不存在的
type属性:你的数组元素是直接包含createdAt、status、end的,不需要通过type来访问,直接用a.createdAt、a.status、a.end就可以 - 最后一个排序条件逻辑错误:你写的
Date.parse(a[type].end) - Date.parse(a[type].end)是同一个值相减,结果永远为0,等于没加这个升序条件,应该是Date.parse(a.end) - Date.parse(b.end) - 排序优先级需要严格匹配你的需求层级:先按
createdAt降序,再按status降序,最后按end升序
正确的排序代码
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'}, ]; // 执行排序 items.sort((a, b) => { // 1. 按createdAt降序:新的日期在前 const dateDiff = new Date(b.createdAt) - new Date(a.createdAt); if (dateDiff !== 0) { return dateDiff; } // 2. createdAt相同则按status降序:数值大的在前 const statusDiff = b.status - a.status; if (statusDiff !== 0) { return statusDiff; } // 3. status也相同则按end升序:早的日期在前 return Date.parse(a.end) - Date.parse(b.end); }); console.log(items);
代码逻辑解释
- createdAt降序:用
new Date(b.createdAt) - new Date(a.createdAt),如果结果不为0,直接返回这个差值,这样新创建的元素会排在前面 - status降序:当createdAt相同时,用
b.status - a.status,数值大的status会排在前面 - end升序:当前两个条件都相同时,用
Date.parse(a.end) - Date.parse(b.end),日期更早的元素会排在前面
执行这段代码后,得到的结果和你期望的完全一致:
[ { 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'}, ]
内容的提问来源于stack exchange,提问作者tigerJK
相关产品推荐
相关产品推荐

