Say you have the following object in JS:
let obj = {a: 24, b: 12, c:21; d:15};
How can 'obj' be transformed into an array of the keys of the object, sorted by the values?
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((a, b) => obj[a] - obj[b]);
console.log(keys);
Note that the above could 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 to sort in the opposite direction.
compareFunction.Object.keys() returns an array. You can do the above in one line if desired, as Object.keys(obj).sort(...). @Blender - Yes, but it doesn't. We can't really define a generic sort comparator to cater to all types, because the values could be nested objects or...anything.here is the way to get sort the object and get sorted object in return
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 customise your sorting function as per your requirement