Sometimes, we need to sort JavaScript objects by their values.
In this article, we’ll look at various ways to do that in our JavaScript programs.
Sort JavaScript Object Property by Values with Object.entries and Array Methods
We can use JavaScript methods that are built into the Object
constructor to get the keys and values of an object as an array.
And then we can use array methods to rearrange them.
For instance, we can write:
const ages = {
james: 10,
jane: 9,
bob: 30
}
const sorted = Object.entries(ages)
.sort(([, v1], [, v2]) => v1 - v2)
.reduce((obj, [k, v]) => ({
...obj,
[k]: v
}), {})
console.log(sorted)
We use the Object.entries
method to get an array of array of key-value pairs in from the ages
object.
Then we call sort
with a callback to sort the values which we destructured from the array returned from Object.entries
.
And then we call reduce
with a callback to merge the obj
object with the k
and v
key-value pair.
The 2nd argument should be set to an object so we can do the object spread initially.
Therefore, sorted
should be:
{jane: 9, james: 10, bob: 30}
Instead of using reduce
, we can also use Object.fromEntries
to convert the sorted array back to an object.
For instance, we can write:
const ages = {
james: 10,
jane: 9,
bob: 30
}
const sortedArr = Object.entries(ages)
.sort(([, v1], [, v2]) => v1 - v2)
const sorted = Object.fromEntries(sortedArr)
console.log(sorted)
Object.fromEntries
takes an array of array of key-value pairs. The keys are put into the object as property names.
And the values are their corresponding values.
Therefore, we should get the same result as before but written in a shorter way.
Object.keys
Another way to sort an object’s properties by their property values is to get the keys from the Object.keys
method.
Then we can do the sorting the same way.
For instance, we can write:
const ages = {
james: 10,
jane: 9,
bob: 30
}
const sorted = Object.keys(ages)
.sort((key1, key2) => ages[key1] - ages[key2])
.reduce((obj, key) => ({
...obj,
[key]: ages[key]
}), {})
console.log(sorted)
Object.keys
only return the property name strings of the ages
object, so in the sort
callback, we’ve to get the value from the ages
object to do the sorting.
Also, we’ve to do the same thing in the reduce
callback to get the object value from ages
.
And at the end, sorted
should be the same as in the previous example.
Conclusion
We can use native JavaScript object and array methods to let us sort properties by their values.