【发布时间】:2019-12-05 23:49:05
【问题描述】:
我有以下对象数组:
const items = [
{ name: "Different Item", amount: 100, matches: 2 },
{ name: "Different Item", amount: 100, matches: 2 },
{ name: "An Item", amount: 100, matches: 1 },
{ name: "Different Item", amount: 30, matches: 2 }
]
我需要将这些按matches 和amount 排序,所以最终结果如下所示:
[
{ name: "Different Item", amount: 100, matches: 2 },
{ name: "Different Item", amount: 100, matches: 2 },
{ name: "Different Item", amount: 30, matches: 2 },
{ name: "An Item", amount: 100, matches: 1 }
]
首要任务是按matches 对所有内容进行排序,然后在其中,我需要按amount 对它们进行排序。我知道我可以按 matches 或 amount 排序,如下所示:
items.sort((a, b) => a.matches - b.matches);
但是我怎样才能同时按两者排序呢?
【问题讨论】:
-
items.sort(1.按匹配排序。2a.如果相等,按数量排序。2b.如果不相等,不做数量排序。)。也就是说,相等的“匹配”不会解决或多或少的问题,因此请转到下一个排序。对所有排序条件重复此模式。如果它们都解析为相等,则 2 项相等,Javascript 不会更改它们的顺序。一旦一个排序解决了“不等于”,那么我们就知道哪个是 lesser.greater - 无论后续标准如何解决。
标签: javascript arrays sorting