Here is my dictionary:
const dict = {
\"x\" : 1,
\"y\" : 6,
\"z\" : 9,
\"a\" : 5,
\"b\" : 7,
\"c\" : 11,
\"d\" : 17,
\"t\" : 3
};
The answer provided by @thefourtheye works to an extent, but it does not return the same "dictionary" structure.
If you want to return a sorted object with the same structure you started with, you can run this on the items 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 a single 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)
}
Example:
Simply pass your object into 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)
})