References
- How to sort an array of integers correctly
- Sort JavaScript object by key
- JavaScript assoc array with negative int keys
I am trying to sort an object by its keys, numerically. As you can see here, while the object keys come out of the sort callback correctly, they object keys still end up in the wrong order when using negative numbers.
let originalObject = {100:'a', 300:'b', '-900':'c', 400:'d'};
document.write(
'<br />' + JSON.stringify(Object.keys(originalObject)
.sort((a, b) => parseInt(a) - parseInt(b))
.reduce(
(obj, key) => {
document.write('Adding key '+key+'<br />');
obj[key] = originalObject[key];
return obj;
},
{}
))
);
Output:
Adding key -900
Adding key 100
Adding key 300
Adding key 400
{"100":"a","300":"b","400":"d","-900":"c"}
I can correct this by forcing the keys to be strings. (Though, even key.toString()
doesn't work. You must do something like key+'-sorted'
.
let originalObject = {100:'a', 300:'b', '-900':'c', 400:'d'};
document.write(
'<br />' + JSON.stringify(Object.keys(originalObject)
.sort((a, b) => parseInt(a) - parseInt(b))
.reduce(
(obj, key) => {
document.write('Adding key '+key+'<br />');
obj[key+'-sorted'] = originalObject[key];
return obj;
},
{}
))
);
Output:
Adding key -900
Adding key 100
Adding key 300
Adding key 400
{"-900-sorted":"c","100-sorted":"a","300-sorted":"b","400-sorted":"d"}
Is there a way to put negative-number object keys at the beginning of an object?