如何在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);
逻辑说明
- Matched字段排序:布尔值
true转为数字是1,false是0,用b的Matched数值减去a的,就能实现降序(true元素排在前面)。 - TotalHealth字段排序:当两个元素的
Matched值相同时,进入这一步比较。用b.TotalHealth减去a.TotalHealth,数值大的元素会排在前面,实现降序。 - 排序优先级:
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
相关产品推荐
相关产品推荐

