The answer provided by @thefourtheye works to some extent, but it does not return the same "dictionary" structure.
If you want to return a sorted object with the same structure with which you started , you can do this for elements returned from the accepted answer:
sorted_obj={} $.each(items, function(k, v) { use_key = v[0] use_value = v[1] sorted_obj[use_key] = use_value })
Combine them for one function that sorts a JavaScript object :
function sort_object(obj) { items = Object.keys(obj).map(function(key) { return [key, obj[key]]; }); items.sort(function(first, second) { return second[1] - first[1]; }); sorted_obj={} $.each(items, function(k, v) { use_key = v[0] use_value = v[1] sorted_obj[use_key] = use_value }) return(sorted_obj) }
An example :
Just pass your object to the sort_object function :
dict = { "x" : 1, "y" : 6, "z" : 9, "a" : 5, "b" : 7, "c" : 11, "d" : 17, "t" : 3 }; sort_object(dict)
Result :
{ "d":17, "c":11, "z":9, "b":7, "y":6, "a":5, "t":3, "x":1 }
"Proof" :
res = sort_object(dict) $.each(res, function(elem, index) { alert(elem) })