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;
});
});