-2

The code below sorts the list from 1->3 but I'm looking to maintain a second bounding condition.

list = [{
  "id": 3,
  "coolpoints": 30
}, {
  "id": 2,
  "coolpoints": 50
}, {
  "id": 2,
  "coolpoints": 30
}, {
  "id": 1,
  "coolpoints": 20
}]



listB = (list.sort((a, b) => (a.id > b.id) ? 1 : -1))

console.log(listB)

How can you add a second condition so id stays sorted this way but coolpoints is sorted as well.

[
  {
    "id": 1,
    "coolpoints": 20
  },
  {
    "id": 2,
    "coolpoints": 30  <----- should be 50
  },
  {
    "id": 2,
    "coolpoints": 50  <----- should be 30
  },
  {
    "id": 3,
    "coolpoints": 30
  }
]
Jay
  • 117
  • 1
  • 9

1 Answers1

1

You can use OR condition and pass the second condition in case of tie.

const list = [{ "id": 3, "coolpoints": 30 }, { "id": 2, "coolpoints": 50 }, { "id": 2, "coolpoints": 30 }, { "id": 1, "coolpoints": 20 }];
list.sort((a, b) => a.id - b.id || b.coolpoints - a.coolpoints)
console.log(list)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51