代码之家  ›  专栏  ›  技术社区  ›  APixel Visuals

JavaScript-按两个整数属性对数组排序[重复]

  •  2
  • APixel Visuals  · 技术社区  · 5 年前

    我有以下对象数组:

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

    第一要务是按 比赛 ,然后在这些里面,我需要按 数量 . 我知道我可以 比赛 或者只是 数量 就像这样:

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

    但我怎么能两者兼顾呢?

    2 回复  |  直到 5 年前
        1
  •  3
  •   kind user Faly    5 年前

    你可以用 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);
        2
  •  0
  •   Dacre Denny    5 年前

    另一种基于两个临界点的排序方法 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);