Before I sort I can access array values by key correctly.
var a=[];
a['1']={'id':'1','aaa':'xxx'}
a['2']={'id':'2','bbb':'yyy'}
document.write(a['1'].id+' '+a['2'].id+'<br>')
After the sort, the keys turn into indexes:
a.sort(function(a, b) {
var x = a.id;
var y = b.id;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
alert('a["1"]='+a['1'].id+'\n\na["2"]='+a['2'])
a[“2”] becomes undefined. Where is the problem? Is sorting incorrect?
Here is example:
http://jsfiddle.net/TJLtS/1/
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 isa[1]. There is noa[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. Usingalertis 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:
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
Keep All Objects in a Hash, with Separate Ordering