0

I don't know exactly how to explain it, but this is what I want. I have an array of domains also containing a health value and this is how I want to sort it. If the health value is unknown, currently healthKnown is set to false and health is set to 95.

aaa.com - 100
bbb.com - 100
ccc.com - 100
aaa.com - 90
bbb.com - 90
ccc.com - 90
aaa.com - (unknown)
bbb.com - (unknown)
ccc.com - (unknown)

(there wouldn't be any duplicates though)

In this, each set of domains with the same health are alphabetically sorted and unknown health is last. The array looks like this.

[
  {
    "name": "example1.com",
    "details": ...,
    "health": 100,
    "healthKnown: true
  },
  {
    "name": "example2.com",
    "details": ...,
    "health": 100,
    "healthKnown: true
  }
]
Jacob
  • 1
  • 1

1 Answers1

1

as per comments, array.sort() is probably the best way to go. See an example

let domains = [
  {
    "name": "a.example1.com",
    "details": "",
    "health": 100,
    "healthKnown": true
  },
  {
    "name": "c.example2.com",
    "details": "",
    "health": 100,
    "healthKnown": true
  },
  {
    "name": "b.example2.com",
    "details": "",
    "health": 100,
    "healthKnown": true
  }
]

domains
  .sort((a,b) => b.healthKnown && a.health > b.health ? 1 : -1)
  // credits to https://stackoverflow.com/a/61033232/833499
  .sort((a, b) => a.name.localeCompare(b.name))
console.log(domains);
lcapra
  • 1,420
  • 16
  • 18