Your problem is that arrays in JavaScript are 0-based, not 1-based. After you sort, your first element is a[0]
and your second is a[1]
. There is no a[2]
, after sorting.
You could see this yourself if you would open your Developer Tools in your browser—all modern browsers have them; Google if you need help finding it—and adding the code console.log(a)
after sorting. Using alert
is about the most painful and least efficient possible way to debug your code.
Here's an updated version of your script, working: http://jsfiddle.net/TJLtS/2/
Also, for future reference you may wish to declare your object literals more simply:
var a = [
{id:'1', aaa:'xxx'}, // This is a[0]
{id:'2', bbb:'yyy'} // This is a[1]
];
As you can see, keys that are legal identifiers do not need to be quoted in object literals.
Edit Here are two alternatives you might be interested in, depending on your needs:
Keep All Objects in a Sorted Array
var objects = [
{id:"a1", name:"Jim"},
{id:"a2", name:"Zed"},
{id:"a3", name:"Bob"},
];
objects.sort(function(o1,o2){
var n1 = o1.name, n2 = o2.name;
return n1<n2 ? -1 : n1>n2 ? 1 : 0;
});
for (var i=0,len=objects.length; i<len; ++i ){
console.log( objects[i].id );
}
// Result:
// a3, a1, a2
Keep All Objects in a Hash, with Separate Ordering
var objects = {
a1: {id:"a1", name:"Jim"},
a2: {id:"a2", name:"Zed"},
a3: {id:"a3", name:"Bob"},
};
// Easily look up an object by id (can't do this as easily or fast with array)
var id = "a2";
console.log( objects[id] ); // {id:"a2", name:"Zed"}
// Create an array just the ids
var ids = Object.keys(objects);
// Sort the array of ids based on properties of the objects the represent
ids.sort(function(id1,id2){
var n1 = objects[id1].name, n2=objects[id2].name;
return n1<n2 ? -1 : n1>n2 ? 1 : 0;
});
// Iterate the sorted array and use each key to find the object
for (var i=0,len=ids.length; i<len; ++i){
console.log( objects[ids[i]].name );
}
// Result:
// Bob, Jim, Zed