I have an Array like the following, how would I sort it by the keys of the objects it contains?
var myArray = [
item : {
},
anotherItem : {
}
];
EDIT
myArray
is an Object not an Array. Does that change anything?
I have an Array like the following, how would I sort it by the keys of the objects it contains?
var myArray = [
item : {
},
anotherItem : {
}
];
EDIT
myArray
is an Object not an Array. Does that change anything?
In Javascript, arrays can only be declared with numeric keys and objects can be declared with alphanumeric keys (attributes).
It may help to take a look at Javascript's array sort()
method.
However, although there is not a way to declare an array with non-numeric keys, as icktoofay has pointed out, since arrays are a special type of object, it is possible to set non-numeric keys for arrays after they have been declared.
First of all, that syntax is invalid: there is no way to set a key in an array literal. Additionally, while it is possible, you probably do not want an array with non-numeric properties; arrays are designed to hold numeric properties.
Even if those were corrected, properties in an object have no defined iteration order:
The mechanics and order of enumerating the properties […] is not specified.
Sorting, by definition, affects the order; if there is no defined order in the first place, you cannot really change it.