Search code examples
javascriptarrayssortingjavascript-objectsin-place

Is array.sort() in-place even when operating on Object.keys()?


The .sort() method of JavaScript arrays modifies the array in-place and returns a reference to the array.

Object.keys(obj) gets an array which contains all the keys of the object obj.

In JavaScript, object keys are stated in the standards not to be in any specific order.

So the two "rules" seem to conflict: "array.sort() is in-place" vs "Object keys are not ordered".

When we call Object.keys(obj).sort() which of the following happens?

  • The keys of the object were sorted in place and stay sorted if the object isn't modified?
  • A temporary anonymous copy of the array of object keys is created and sorted?
  • Something else?

Is this documented in the standard or does it vary by implementation?


Solution

  • The answer is the second: A temporary anonymous copy of the array of object keys is created and sorted.

    The ecma spec states that the result value of Object.keys must be a new instance of an array every time. That means the resulting array is not backed by the actual keys of the object, it's not like Java's keySet, it's just a copy.