Sometimes, we want to sort arrays in JavaScript by object key value.
In this article, we’ll look at how to sort arrays in JavaScript by object key value.
Sort Arrays in JavaScript by Object Key Value
To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort
method.
For instance, we can write:
const arr = [{
name: "alex"
}, {
name: "clex"
}, {
name: "blex"
}];
const sorted = arr.sort((a, b) => (a.name > b.name ? 1 : -1))
console.log(sorted)
to sort the arr
array by the value of the name
properties.
We call arr.sort
with a callback that compare the name
properties of entries a
and b
in the arr
object.
If a.name
is bigger than b.name
, we return 1.
Otherwise, we return -1.
The comparison operator will compare 2 string’s by their lexical order.
Therefore, sorted
is:
[
{
"name": "alex"
},
{
"name": "blex"
},
{
"name": "clex"
}
]
Conclusion
To sort arrays in JavaScript by object key value, we can use the JavaScript array’s sort
method.