Given an object with unsorted numeric values, such as:
const unsorted = {
green: 80,
blue: 90,
red: 30,
yellow: 100,
}
We want a data structure with the same key/value pairs sorted in descending order of the values, e.g.:
const sorted = {
yellow: 100,
blue: 90,
green: 80,
red: 30,
}
My solution:
function sortObjectByValue (obj) {
const sorted = Object.keys(obj)
.sort((a, b) => obj[b] - obj[a])
.reduce((acc, cur) => {
acc[cur] = obj[cur]
return acc
}, {})
return new Map(Object.entries(sorted))
}
What I hope could be improved:
- Two iterations, first
sort
thenreduce
; this seems inefficient. - Using
Map
. I wish we could just use objects, it would make using this elsewhere much easier. I doubt this can be avoided though, as we need to ensure that the order is preserved.