How to sort objects by value
3 answers
let obj = {a: 24, b: 12, c:21, d:15};
// Get an array of the keys:
let keys = Object.keys(obj);
// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] - obj[b] });
console.log(keys);
Note that the above can be done in one line if desired with Object.keys(obj).sort(...)
. The simple .sort()
comparator function shown will only work for numeric values (swap a
and b
for sorting in the opposite direction), but since in this question I am assuming this is fine ...
+5
source to share
here is a way to get sorted object and get sorted object in reverse order
let sortedObject = {}
sortedObject = Object.keys(yourObject).sort((a, b) => {
return yourObject[a] - yourObject[b]
}).reduce((prev, curr, i) => {
prev[i] = yourObject[curr]
return prev
}, {});
you can customize your sorting function as per your requirement
0
source to share