【问题标题】:JavaScript - Sort array by two integer properties [duplicate]JavaScript - 按两个整数属性对数组进行排序[重复]
【发布时间】: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 }
]

我需要将这些按matchesamount 排序,所以最终结果如下所示:

[
    { 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 对它们进行排序。我知道我可以按 matchesamount 排序,如下所示:

items.sort((a, b) => a.matches - b.matches);

但是我怎样才能同时按两者排序呢?

【问题讨论】:

  • items.sort(1.按匹配排序。2a.如果相等,按数量排序。2b.如果不相等,不做数量排序。)。也就是说,相等的“匹配”不会解决或多或少的问题,因此请转到下一个排序。对所有排序条件重复此模式。如果它们都解析为相等,则 2 项相等,Javascript 不会更改它们的顺序。一旦一个排序解决了“不等于”,那么我们就知道哪个是 lesser.greater - 无论后续标准如何解决。

标签: javascript arrays sorting


【解决方案1】:

您可以使用Array#sort。对象将首先根据matches 排序,然后根据amount

const items = [
    { name: "Different Item", amount: 90, matches: 2 },
    { name: "Different Item", amount: 100, matches: 1 },
    { name: "An Item", amount: 80, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 },
    { name: "Different Item", amount: 40, matches: 1 },
    { name: "Different Item", amount: 50, matches: 1 },
    { name: "An Item", amount: 10, matches: 1 },
    { name: "Different Item", amount: 20, matches: 2 },
];

const r = [...items].sort((a, b) => b.matches - a.matches || b.amount - a.amount);

console.log(r);

【讨论】:

  • 完美运行,谢谢!我会在 10 分钟后接受答案
  • 使用r 有点误导。 items 已就地排序。
  • @xehpuk 你是绝对正确的,添加一个价差以防万一是不变的事情
【解决方案2】:

使用Array#sort 表达基于两个条件的排序的另一种方式是:

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 }
]

const result = items.sort((a, b) => {
  
  const matches = b.matches - a.matches;
  
  // If a.matches and b.matches are not the same,
  // sort this a and b pair based on matches in
  // descending order
  if(matches !== 0) {
    return matches;
  }
  
  // Here, the a and b pair have the same matches
  // value, so sort based on seondary criteria; 
  // amount in descending order
  return b.amount - a.amount;
});

console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2020-10-06
    相关资源
    最近更新 更多