How can I sort objects by the value of one of the keys

Viewed 18

So I've been trying to sort the following object and ive been having some trouble:

let obj = {
 "1": {
  "name": "card1",
  "ryo": 3
},
"2": {
  "name": "card2",
  "ryo": 7
},
 "3": {
  "name": "card3",
  "ryo": 2
  }
}

Object.fromEntries(Object.entries(obj).sort((x, y) => y[1].ryo - x[1].ryo));

The code above returns:

{
  '1': { name: 'card1', ryo: 3 },
  '2': { name: 'card2', ryo: 7 },
  '3': { name: 'card3', ryo: 2 }
}

my goal is to get it to return:

{
  '2': { name: 'card2', ryo: 7 },
  '1': { name: 'card1', ryo: 3 },
  '3': { name: 'card3', ryo: 2 }
}

As simple as it seems I just cant get it to work and I dont know why it wont sort.

Edit: Id like to add that im trying to sort the object by ryo in descending order.

1 Answers

You can try converting to an array then sorting like this

let sorted = Object.entries(obj).sort(function(a, b) {
return b[1].ryo - a[1].ryo
});
Related