Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a dictionary by numerical value of key in javascript

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading