I have an Object of Objects. (because I want to use associative array, so object of objects, not numeric array of objects)
var tasks=new Object();
for(...){
tas
You can pass a function to the sort method of the Array object, which is used to determine the order of the objects in the array. By default, it does this alphabetically and numerically but the numerical way is a bit messed up. Here is how I'd solve your case, assuming that the indexes you're using to sort them are numerical:
tasks.sort(function(obj1,obj2){
return obj1.index - obj2.index;
});
The function passed to the sort method should return a positive integer if object1>object2, 0 if object1=object2, and a negative integer if object1
Perhaps there is a more elegant way, but this way gets all the tasks keys out of the object, sorts them and then uses the ordered index array to cycle through the original object in key order (if I understood correctly what you're trying to do).
var indexArray = [];
var i;
for (i in tasks) {
indexArray.push(i); // collect all indexes
}
indexArray.sort(function(a,b) {return(a-b);}); // sort the array in numeric order
for (i = 0; i < indexArray.length; i++) {
console.log(tasks[indexArray[i]].name);
}
You could use tasks.keys as a shortcut to getting the object indexes, but that is not universally available so you'd have to have an alternate way of doing it anyway.
Reading your question again, I realized that there may be another way to interpret your question. Perhaps you meant in index order where it's the .index data right next to the .name, not the index key on the tasks object. If so, that would take a different routine:
var sorted = [];
var i;
for (i in tasks) {
sorted.push(tasks[i]); // collect items from tasks into a sortable array
}
sorted.sort(function(a,b) {return(a.index - b.index);}); // sort the array in numeric order by embedded index
for (i = 0; i < sorted.length; i++) {
console.log(sorted[i].name);
}
You could stick all names in a temp array and then call the sort()
method on that array.
Check this link
Regards