I have a collection of objects in JavaScript like this:
Object collection = new Object();
collection[123] = new Item(); //another object
collection[425] = new Item();
collection[2134] = new Item();
//etc. etc.
//TODO: sort items
I would like to sort this collection according to the properties of the Item objects in collection. There is good built-in sort function in JS Array, so my first idea was to modify the code followingly:
Object collection = new Array();
collection[123] = new Item(); //another object
collection[425] = new Item();
collection[2134] = new Item();
//etc. etc.
collection.sort(comparisonFunction); //where comparisonfunction handles the sorting logic
Now the collection is nicely sorted - however, I cannot access the items using the property, which I used to set them, i.e.
collection[2134]
is null, because the JS array does not contain that many elements (and even if it would, the result would not be as expected)
What I need is the
- ability to access elements in collection directly with the numerical property I set them (which is already a given, when not using a JS Array)
- ability to sort the items in the collection
Edit: the object does not need to behave like an array and it is not an array of nature. What I need is pretty close to Java TreeMap - a collection, which maintains a specific order, and which is also a map. Or explained in another way, I need a plain old JavaScript object (which some people know as "associative array") whose contained user-created elements can be sorted.
Edit 2: the solution I ended up using is Anatoliy's, slightly modified. Basically I create an array, where I duplicate the "collection" and map the two objects (array and collection) to get the benefits of both. Also thanks to Roatin Marth for pointing out that iterating objects are not guaranteed to happen in any kind of order (I did consider this when modifying Anatoliy's solution).