Sort an array of items by given key
Return a copy sorted by one field, ascending.
function sortBy({ values, key }) { return [...values].sort((a, b) => (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0)); }
Input & expected output
Input
{
"values": [
{
"status": "deferred"
},
{
"status": "bounced"
},
{
"status": "delivered"
}
],
"key": "status"
}Expected output
[
{
"status": "bounced"
},
{
"status": "deferred"
},
{
"status": "delivered"
}
]The edge case
Input
{
"values": [],
"key": "status"
}Expected output
[]Know the limits
- Mixed types compare unpredictably; keep the field one type.
- Sorting is stable, so equal keys keep their order.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Sort an array of items by given key from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Copies with spread instead of concat. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.