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
  }
]
3
  • 1
    Have you tried anything? Show your attempt. Commented Feb 26, 2021 at 9:12
  • you need to use array.sort() Commented Feb 26, 2021 at 9:18
  • @axiac pastebin.com/bBb2eiKH Commented Feb 26, 2021 at 20:30

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

That does sort it correctly by health, but it doesn't sort it alphabetically as well.
It's just an example. Add a subsequent .sort() ordering by name and you are done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.