So for a little context, my object is
const obj: {[key: string]: any} = {
"1000": {
"time": "2022-05-14T10:00:00:000Z",
"availableSlots": 0,
"availability": false
},
"1400": {
"time": "2022-05-14T14:00:00:000Z",
"availableSlots": 4,
"availability": true
},
"0800": {
"time": "2022-05-14T08:00:00:000Z",
"availableSlots": 3,
"availability": true
},
"0830": {
"time": "2022-05-14T08:30:00:000Z",
"availableSlots": 2,
"availability": true
}
}
and I want my object sorted by the key. When I sort my Object entries, I'm able to sort them by keys by using
const x = Object.entries(obj).sort((a,b): number => {
if (parseInt(a[0]) > parseInt(b[0])) {
return 1
} return -1
})
But when I try to reduce it to make it into an object again, it's not sorted again
const x = Object.entries(obj).sort((a,b): number => {
if (parseInt(a[0]) > parseInt(b[0])) {
return 1
} return -1
}).reduce((prev, [hour, hourInfo]) => ({ ...prev, [hour]: hourInfo }), {})
Online Compiler of the problem: link
I'll compare times with the time field using dayjs but for the online compiler I used the keys for an easier comparison