sort_by
Sort an array of objects by a property
Definition
array[any] sort_by(array[any] $array, expression->[number | string] $expression)
Sorts input in ascending order based on the value of $expression
. It can be an object property, or a function evaluating the $array
elements.
Parameters
array[any] $array
The array to sort.
expression->[number|string]$expression
Expression to evaluate the $array
elements on. They are sorted ascending according to the evaluation, which must yield a number or a string.
Returns
array
Input array sorted using $expression
.
Examples
{
"people": [
{"name": "Julia", "age": 30},
{"name": "Alexander", "age": 57},
{"name": "Pete", "age": 71},
{"name": "Selma", "age": 42}
]
}
{
byName: sort_by(people, name),
byAge: sort_by(people, age),
byNameLength: sort_by(people, length(name))
}
{
"byName": [
{"name": "Alexander", "age": 57},
{"name": "Julia", "age": 30},
{"name": "Pete", "age": 71},
{"name": "Selma", "age": 42}
],
"byAge": [
{"name": "Julia", "age": 30},
{"name": "Selma", "age": 42},
{"name": "Alexander", "age": 57},
{"name": "Pete", "age": 71}
],
"byNameLength": [
{"name": "Pete", "age": 71},
{"name": "Julia", "age": 30},
{"name": "Selma", "age": 42},
{"name": "Alexander", "age": 57}
]
}
Updated 11 months ago