Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created November 30, 2023 10:45
Show Gist options
  • Save ChathuraGH/84a59b741af8d502636fbe317d749be8 to your computer and use it in GitHub Desktop.
Save ChathuraGH/84a59b741af8d502636fbe317d749be8 to your computer and use it in GitHub Desktop.
Sort Dictionary to Dictionary Js
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)
}
dict = {
"x" : 1,
"y" : 6,
"z" : 9,
"a" : 5,
"b" : 7,
"c" : 11,
"d" : 17,
"t" : 3
};
res = sort_object(dict)
console.log(res)
//source
//https://stackoverflow.com/questions/25500316/sort-a-dictionary-by-value-in-javascript
//https://stackoverflow.com/a/53530097/13861187
@ChathuraGH
Copy link
Author

Order can't be guaranteed because dictionary objects have no ordering.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment