sort_by

Modified on Thu, 9 Jul at 10:49 AM

sort_by

TABLE OF CONTENTS

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

Sample data
{
  "people": [
    {"name": "Julia", "age": 30},
    {"name": "Alexander", "age": 57},
    {"name": "Pete", "age": 71},
    {"name": "Selma", "age": 42}
  ]
}
Transformation
{
  byName: sort_by(people, name),
  byAge: sort_by(people, age),
  byNameLength: sort_by(people, length(name))
}
Result
{
  "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}
  ]
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article