Created
November 30, 2023 10:45
-
-
Save ChathuraGH/84a59b741af8d502636fbe317d749be8 to your computer and use it in GitHub Desktop.
Sort Dictionary to Dictionary Js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Order can't be guaranteed because dictionary objects have no ordering.