javascript - Sorting Object by sub-object property -


i have object of objects, i'd sort property... having trouble wrapping head around it:

sample = {     "elem1": { title: "developer", age: 33 },     "elem2": { title: "accountant", age: 24 },     "elem3": { title: "manager", age: 53 },     "elem4": { title: "intern", age: 18} } 

my expected result object keys ordered elem4, elem2, elem1, elem3. alternatively, i'd fine returning keys in order rather physically sorting object.

is more trouble it's worth, or missing obvious (or not-so-obvious) javascript-fu make light work of this?

thanks!

properties (keys) of object not intrinsically ordered; must maintain own array of ordering if wish so.

here example of how simplify ordering sample object arbitrary properties via custom sort functions:

var orderkeys = function(o, f) {   var os=[], ks=[], i;   (i in o) {     os.push([i, o[i]]);   }   os.sort(function(a,b){return f(a[1],b[1]);});   (i=0; i<os.length; i++) {     ks.push(os[i][0]);   }   return ks; };  orderkeys(sample, function(a, b) {   return a.age - b.age; }); // => ["elem4", "elem2", "elem1", "elem3"]  orderkeys(sample, function(a, b) {   return a.title.localecompare(b.title); }); // => ["elem2", "elem1", "elem4", "elem3"] 

once properties ordered can iterate them , retrieve corresponding values in order.