You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Script中按两个元素对数组进行降序排序?

Google Script 数组多条件排序实现

你的需求是先按Matched字段降序排序(true排在false前面),再按TotalHealth字段降序排序(数值大的在前),可以通过数组的sort()方法结合自定义比较函数实现,具体代码如下:

实现代码

// 你的原始数组
const enemies = [
  {RowOfEnemy: 0.0, BonusType: "", Alive: true, TotalHealth: 4350000.0, Matched: false}, 
  {Alive: true, BonusType: "", Matched: false, TotalHealth: 3900000.0, RowOfEnemy: 1.0}, 
  {Matched: true, Alive: true, TotalHealth: 3780000.0, RowOfEnemy: 2.0, BonusType: "MELEE"}
];

// 多条件排序
enemies.sort((a, b) => {
  // 先比较Matched字段,降序
  const matchedDiff = (b.Matched ? 1 : 0) - (a.Matched ? 1 : 0);
  if (matchedDiff !== 0) {
    return matchedDiff;
  }
  // 如果Matched相同,再比较TotalHealth字段,降序
  return b.TotalHealth - a.TotalHealth;
});

// 输出排序后的数组
console.log(enemies);

逻辑说明

  1. Matched字段排序:布尔值true转为数字是1,false是0,用b的Matched数值减去a的,就能实现降序(true元素排在前面)。
  2. TotalHealth字段排序:当两个元素的Matched值相同时,进入这一步比较。用b.TotalHealth减去a.TotalHealth,数值大的元素会排在前面,实现降序。
  3. 排序优先级:sort()方法会先处理第一个条件的排序差异,只有当第一个条件完全相同时,才会触发第二个条件的比较,完美契合你的需求。

运行这段代码后,排序结果会是:

[
  {Matched: true, Alive: true, TotalHealth: 3780000.0, RowOfEnemy: 2.0, BonusType: "MELEE"},
  {RowOfEnemy: 0.0, BonusType: "", Alive: true, TotalHealth: 4350000.0, Matched: false},
  {Alive: true, BonusType: "", Matched: false, TotalHealth: 3900000.0, RowOfEnemy: 1.0}
]

内容的提问来源于stack exchange,提问作者Richard Hommel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:31:17