Home > front end >  Sort a dictionary by numerical value of key in javascript
Sort a dictionary by numerical value of key in javascript

Time:07-25

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

CodePudding user response:

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)

CodePudding user response:

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"

  • Related