Home > Blockchain >  How to sort an array by 2 elements in google script
How to sort an array by 2 elements in google script

Time:09-18

I am using google script and I have an array like so

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

I want to sort on Matched and then TotalHealth both descending. I know how to sort on a single element but I am stumped on sorting 2 elements. Any help would be appreciated.

CodePudding user response:

How about the following sample script?

Sample script:

const obj = [{ 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" }];
obj.sort((a, b) => a["TotalHealth"] > b["TotalHealth"] ? 1 : -1);
obj.sort((a, b) => a["Matched"] < b["Matched"] ? 1 : -1);
console.log(obj)

When this script is run, the following result is obtained. The values of "Matched" and "TotalHealth" are reordered in descending order.

[
  { Matched: true, Alive: true, TotalHealth: 3780000, RowOfEnemy: 2, BonusType: 'MELEE' },
  { RowOfEnemy: 0, BonusType: '', Alive: true, TotalHealth: 4350000, Matched: false },
  { Alive: true, BonusType: '', Matched: false, TotalHealth: 3900000, RowOfEnemy: 1 }
]

If you want to change this order, please modify < and >.

Reference:

  • Related