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?

Answers


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.


Objects in JavaScript do not have order. You can sort the keys of an object and get an array of the object keys, but you can't sort an object.

var test = {'a': 12, 'c': 99, 'b': 8, 'd': 15};
console.log(Object.keys(test).sort());
// outputs: ["a", "b", "c", "d"]
// but test still remains as: Object {a: 12, c: 99, b: 8, d: 15}

Object.keys(test).sort() gives an array of "a", "b", "c", and "d" in order, but the object is still remains in random order (based on user's browser).

In other words, a temporary anonymous copy of the array of object keys is created and sorted when you call Object.keys(test).sort(), and the object remains unchanged.


Most likely JS will create a temporary anonymous copy of the array of object and it is sorted.


Need Your Help

Opening remote documents in Python

python xml parsing document

from xml.dom.minidom import parse, parseString

Find all possible partitions of n elements with k-sized subsets, where two elements share same set only once

partitioning permutation combinatorics

I have n elements that need to be partitioned into x sets, each set has to hold exactly k=4 elements.