0

References

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.

Codepen

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'.

Codepen

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?

Tyler V.
  • 1,873
  • 16
  • 36
  • 2
    see: [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order), as well as [Why is document.write considered a “bad practice”?](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – pilchard Mar 25 '21 at 22:48
  • 3
    Why do you need it sorted? There are probably better options – epascarello Mar 25 '21 at 22:52
  • 2
    A javascript object with numeric keys will always be stored in numeric sort order no matter the order the keys are set – charlietfl Mar 25 '21 at 22:53
  • The negative numbers are not considered numbers by the mechanism that returns property names in canonical order. The positive integer property names always come first. There's really no point in even thinking about ordering property names in JavaScript; if you need an ordering, get the names with `Object.keys()`, sort them however you want, then access the properties via numeric indexes into the array. – Pointy Mar 25 '21 at 22:57

1 Answers1

0

You can always use an array which clearly communicates a specific order so u don't have to deal with hacky browser specific behavior of object key insertion, for example this will always work:

const data = Object.entries({ 100: 'a', 300: 'b', '-900': 'c', 400: 'd' });

const sorted = [...data].sort((a, b) => parseInt(a[0]) - parseInt(b[0]) )

console.log(sorted)
marcos
  • 4,099
  • 1
  • 6
  • 18