Twig Components / Methods / sort
Note: You are currently reading the documentation for Bolt 5.0. Looking for the documentation for Bolt 5.2 instead?
sort(arrow = null)
is a Twig filter to sort an array:
{% for user in users|sort %}
...
{% endfor %}
Note: Internally, Twig uses the PHP [asort](https://www.php.net/asort) function to maintain index association. It supports Traversable objects by transforming those to arrays.
You can pass an arrow function to sort the array:
{% set fruits = [
{ name: 'Apples', quantity: 5 },
{ name: 'Oranges', quantity: 2 },
{ name: 'Grapes', quantity: 4 },
] %}
{% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
{{ fruit }}
{% endfor %}
{# output in this order: Oranges, Grapes, Apples #}
Note the usage of the spaceship operator to simplify the comparison.
ArgumentsΒΆ
- arrow: An arrow function
Source: Twig
Edit this page on GitHub
Couldn't find what you were looking for? We are happy to help you in the forum, on Slack or on Github.
Couldn't find what you were looking for? We are happy to help you in the forum, on Slack or on Github.