0

I have this dictionary:

{
  "13.666666666666666": {
    "data": 0
  },
  "1": {
      "data": 0
  },
  "0.5": {
    "data": 0
  }
}

I wish to sort the dictionary so that the keys are in numerical order as such:

{
  "0.5": {
    "data": 0
  },
  "1": {
      "data": 0
  },
  "13.666666666666666": {
    "data": 0
  }
}

How do I sort a dictionary by numerical value of key in javascript? This is for debugging purposes - not for iteration.

I know I can do this for iteration purposes:

const keys = Object.keys(my_dict).sort(function(a, b){return a-b});
for (const key of keys) {
   const value = my_dict[key]
}
etayluz
  • 15,920
  • 23
  • 106
  • 151
  • 1
    Does this answer your question? [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Ivar Jul 24 '22 at 19:29
  • It explains it but doesn't provide a solution to my problem – etayluz Jul 24 '22 at 19:31
  • "_Using an array or a `Map` object can be a better way to achieve this. `Map` shares some similarities with `Object` and guarantees the keys to be iterated in order of insertion, without exception_" - There aren't many more options. – Ivar Jul 24 '22 at 19:32
  • @Ivar I'm actually interested in generating a human readable json with keys in numerical order. It's for debugging purposes. It's not for iteration. – etayluz Jul 24 '22 at 19:33
  • 1
    Life would be way easier if you can make it an array of objects with keys and values. Something like `Object.entries(array).map(([key, value]) => ({key, value})).sort((a, b) => +a.key - +b.key)`. – Ivar Jul 24 '22 at 19:40

2 Answers2

1

Ivar was right: You shouldn't rely on order of keys in object. The following naive approach of sorting the keys into a new object, demonstrates this by not working.

var obj = {
  "13.666666666666666": {
    "data": 0
  },
  "1": {
    "data": 0
  },
  "0.5": {
    "data": 0
  }
}

var result = {}
var arr = Object.keys(obj).sort()

console.log(arr)

arr.forEach(key => result[key] = obj[key]);

console.log(result)
IT goldman
  • 14,885
  • 2
  • 14
  • 28
0

I found a work around!

The workaround is to insert all numerical keys as decimal values - and not a mix of whole and decimal numerical keys.

Then the dictionary will "sort itself" so to speak.

"1" => "1.0"

etayluz
  • 15,920
  • 23
  • 106
  • 151