How would one sort the following object to correct alphabetical order of names?
var users_by_id = { '12': ['Ted', 34, 'Male'], '13': ['Ben', 36, 'Male'], '14': ['Alice', 42, 'Female'] } var users_by_name = { '14': ['Alice', 42, 'Female'], '13': ['Ben', 36, 'Male'], '12': ['Ted', 34, 'Male'] } I have a plan which would need two passes over the object, but I am not sure if there is a simpler way to do it. The plan I have is this (I am using jQuery):
var users_by_name = {}; var names = []; $.each(users_by_id, function(id, props) { names.push(props[0]); }); names.sort(); $.each(names, function(i, n) { $.each(users_by_id, function(id, props) { if(n == props[0]) users_by_name[id] = props; }); });
for-inenumeration of objects has no required order by the ECMAScript spec. It's up to the implementation what order should be used. If a spec wants to enumerate object properties differently every time, they may. The key point is that order must be enforced by your code. This usually involves Arrays since you can enforce order via a numeric iteration.