Reputation:
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?
Upvotes: 11
Views: 25306
Reputation: 150010
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.
Upvotes: 15
Reputation: 945
If the purpose is just monitoring the sorted object in console, I suggest log the object in console with console.table(obj)
instead of console.log(obj)
and the result will be sortable for both key and value, asc and desc in fastest way with no extra process.
Upvotes: -1
Reputation: 1748
Wrapped in a function with ASC or DESC.
const myobj = {a: 24, b: 12, c:21, d:15};
function sortObjectbyValue(obj={},asc=true){
const ret = {};
Object.keys(obj).sort((a,b) => obj[asc?a:b]-obj[asc?b:a]).forEach(s => ret[s] = obj[s]);
return ret
}
console.log(sortObjectbyValue(myobj))
Upvotes: 1
Reputation: 642
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
Upvotes: 1
Reputation: 941
var obj = {
a: 24, b: 12, c:21, d:15
};
var sortable = [];
for (var x in obj ) {
sortable.push([x, obj[x]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
console.log(sortable)
Upvotes: 1