-1

I have the following JSON stored in a variable a in Javascript. This is the JSON

{
   "cow":2,
   "leon": 4,
   "fire":3
}

How can I order from highest to lowest so it looks like this:

{
   "leon": 4,
   "fire":3
   "cow":2,
}

I've tried using the sort () method of Javascript. The problem is that by reviewing I need the key to be the same, for example {object: 3.4, object: 0.4, object: 0.3} to be able to sort it.

How can I do it? I receive this object from an API therefore I can not modify it. Thank you very much.

Ale 99
  • 1
  • 1

1 Answers1

1

Objects are not guaranteed to be in order in Javascript. So there is not way to do what you want, without changing your data structure. You could use an array for example:

const data = [
  ["cow", 2],
  ["leon", 4],
  ["fire", 3],
];

console.log(data.sort((a, b) => b[1] - a[1]))
Phillip
  • 6,033
  • 3
  • 24
  • 34