This question is vital to one of my current projects involving creating HTML tables from JSON objects. I was thinking I could create functions that would sort my Arrays/Objects before rendering them as HTML. My only concern is that order doesn’t matter in JavaScript, and if I were to create a new Array with the same data (in a different order) as another Array they would end up identical.
I can’t think of a fast way to test this, so I’m asking here.
Others have answered on arrays, so I just wanted to provide some info on objects.
On that, the standard is non-existent, but it’s de facto definition is that an object will enumerate in insertion order, with the exception that numbers are placed in ascending order and enumerated first. I say typically, but this behavior is nowhere near standardized (nor do frameworks like jQuery standardize it, AFAIK).
You can test browsers using this jsFiddle:
http://jsfiddle.net/7cCpu/4/
The object
{"foo":"bar", "bar":"foo", "baz":"baz", "3":3, "2":2, "1":1}enumerates as follows:I don’t have Safari installed, but I assume it’s the same as Chrome. In any case, the point is that you can make assumptions — it’s not random — but it’s probably a better idea to use an array if you depend on exact enumeration.
Even nastier is what duri pointed out above, where deleting and replacing the value for a key alters things further. Watch what happens when I
delete barand doObject.bar = "foo"then enumerate: