-3

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?

4
  • 1
    I don't think that's valid... =/ Commented Mar 31, 2013 at 1:39
  • 3
    This is not valid Javascript Array syntax. Commented Mar 31, 2013 at 1:39
  • 1
    possible duplicate of How to sort an array of javascript objects? or Sorting objects in an array by a field value in JavaScript Commented Mar 31, 2013 at 1:43
  • myArray is an Object not an Array - does that change anything? I'm afraid it is neither and is simply invalid syntax. Trying to run your code as is in jsFiddle for example generates Uncaught SyntaxError: Unexpected token : You can see the error in the debugger's console log when running the fiddle. Commented Mar 31, 2013 at 2:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

As an array is an object, it actually can have non-numeric keys, but there is no special syntax for them as there is in plain object literals and it is not treated specially by the array.
@icktoofay - Thanks for pointing out those details about arrays.
Sorry guys, see my edit.
@Aiias, thank you, that first link was exactly what I needed!
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.