Skip to content

Instantly share code, notes, and snippets.

@ChathuraGH
Created November 30, 2023 10:57
Show Gist options
  • Save ChathuraGH/f08ed8d188c05cdd063e44d43ad8f228 to your computer and use it in GitHub Desktop.
Save ChathuraGH/f08ed8d188c05cdd063e44d43ad8f228 to your computer and use it in GitHub Desktop.
Dictionary sort to Dictionary js
class DictUtils {
static entries(dictionary) {
try {
//ECMAScript 2017 and higher, better performance if support
return Object.entries(dictionary);
} catch (error) {
//ECMAScript 5 and higher, full compatible but lower performance
return Object.keys(dictionary).map(function(key) {
return [key, dictionary[key]];
});
}
}
static sort(dictionary, sort_function) {
return DictUtils.entries(dictionary)
.sort(sort_function)
.reduce((sorted, kv)=>{
sorted[kv[0]] = kv[1];
return sorted;
}, {});
}
}
class SortFunctions {
static compare(o0, o1) {
//TODO compelte for not-number values
return o0 - o1;
}
static byValueDescending(kv0, kv1) {
return SortFunctions.compare(kv1[1], kv0[1]);
}
static byValueAscending(kv0, kv1) {
return SortFunctions.compare(kv0[1], kv1[1]);
}
}
let dict = {
"jack": 10,
"joe": 20,
"nick": 8,
"sare": 12
}
let sorted = DictUtils.sort(dict, SortFunctions.byValueDescending)
console.log(sorted);
//source
// https://stackoverflow.com/questions/25500316/sort-a-dictionary-by-value-in-javascript
// https://stackoverflow.com/a/69642627/13861187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment