我想按枚举对数组进行排序,然后按数字排序,然后按日期排序。当我用枚举和数字来做这件事时,它似乎工作得很好,但是当我在最后加上日期时,它会把一切都弄乱了。
这是我的代码:
enum myType {
high,
medium,
low
}
myArray.sort((a, b) =>
myType[a.type] - myType[b.type] ||
a.classification - b.classification ||
new Date(a.time) > new Date(b.time)
? -1
: 1
);
然而,这似乎对相反的含义进行排序,它按类型以相反的顺序排序,即先低后高。我们该怎么做呢?更新:日期将通过:2017-07-02T14:59:55.711Z
最佳答案
不知道time
的风格,您需要包装三元以防止读取三元的所有表达式。
myArray.sort((a, b) =>
myType[a.type] - myType[b.type] ||
a.classification - b.classification ||
(new Date(a.time) > new Date(b.time)
? -1
: 1)
);
通过使用 ISO 8601兼容的字符串,您可以与 String#localeCompare
进行字符串比较.myArray.sort((a, b) =>
myType[a.type] - myType[b.type] ||
a.classification - b.classification ||
a.time.localeCompare(b.time)
);
关于javascript - 按包括日期在内的多个属性对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64670734/