1

I currently have an object like this

let obj = {
    "5": "961131",
    "8": "961127",
    "5,5": "961107",
    "7": "961103",
    "9.5": "961115"
}

Is it possible to sort it by its keys in ascending order? The result I want to achieve would be:

obj = {
    "5": "961131",
    "5,5": "961107",
    "7": "961103",
    "8": "961127",
    "9.5": "961115"
}

It would probably involve creating a new object which I don't mind, just not sure how to get this done

vcosiekx
  • 65
  • 2
  • 9
  • 1
    it is not possible, because the order is defined by index like keys (32 bit positive integer) are sorted first, then all other in insertation order and finally symbols. – Nina Scholz Jun 30 '20 at 17:00
  • 1
    Objects are unordered collections of properties, you cannot sort them. – sp00m Jun 30 '20 at 17:25

2 Answers2

5

You can't. Object keys are not sortable and you can't predict how each browser will iterate through object.

But you can use an array as index like this. Remember to format your keys. If it's a string, juste use .sort(). Else you should probably compare your keys with .sort((a, b) => parseFloat(a) - parseFloat(b));

let obj = {
    "5": "961131",
    "8": "961127",
    "5,5": "961107",
    "7": "961103",
    "9.5": "961115"
}

let index = Object.keys(obj).sort()

// iterate method
index.forEach((key) => {
  console.log(key, obj[key])
})

// or array of sorted object
let sortedArrayOfObject = index.map((v) => {
  return {key: v, value: obj[v]}
})
console.log(sortedArrayOfObject)
GuilleW
  • 417
  • 4
  • 10
  • 1
    You'll want to [sort these numbers](https://stackoverflow.com/q/1063007/1048572) using `.sort((a, b) => parseFloat(a.replace(/,/,'')) - parseFloat(b.replace(/,/,'')))` though – Bergi Jun 30 '20 at 17:21
  • I think keys should be formated before. Because we don't know if keys are string or float (actually, we can see period and comma) – GuilleW Jun 30 '20 at 17:36
  • Yes, the input format is wonky and should be fixed, but still the string keys should not be compared lexically but as numbers. – Bergi Jun 30 '20 at 17:41
  • Btw, regarding the `sortedArrayOfObject`, that format is horrible to work with. Much better would be `{key: v, value: obj[v]}` or `[v, obj[v]]`. – Bergi Jun 30 '20 at 17:42
  • Indeed, I use mine like this too. updating the answer – GuilleW Jun 30 '20 at 23:11
0
let obj = {
    "5": "961131",
    "8": "961127",
    "5,5": "961107",
    "7": "961103",
    "9.5": "961115"
}
const objSortedByKeys = Object.fromEntries(Object.entries(obj).sort((a,b)=>a[0].localeCompare(b[0])));
SUDHIR KUMAR
  • 381
  • 4
  • 10