11

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?

5 Answers 5

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This only works for numeric values, so if your array has other types, you'll have to define the full compareFunction.
Does Object.keys() return an array?
Yes, 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.
1
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)

Comments

1

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

Comments

1

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))

Comments

-1

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. enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.