1``sort``
2========
3
4.. versionadded:: 2.12
5    The ``arrow`` argument was added in Twig 2.12.
6
7The ``sort`` filter sorts an array:
8
9.. code-block:: twig
10
11    {% for user in users|sort %}
12        ...
13    {% endfor %}
14
15.. note::
16
17    Internally, Twig uses the PHP `asort`_ function to maintain index
18    association. It supports Traversable objects by transforming
19    those to arrays.
20
21You can pass an arrow function to sort the array:
22
23.. code-block:: twig
24
25    {% set fruits = [
26        { name: 'Apples', quantity: 5 },
27        { name: 'Oranges', quantity: 2 },
28        { name: 'Grapes', quantity: 4 },
29    ] %}
30
31    {% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
32        {{ fruit }}
33    {% endfor %}
34
35    {# output in this order: Oranges, Grapes, Apples #}
36
37Note the usage of the `spaceship`_ operator to simplify the comparison.
38
39Arguments
40---------
41
42* ``arrow``: An arrow function
43
44.. _`asort`: https://secure.php.net/asort
45.. _`spaceship`: https://www.php.net/manual/en/language.operators.comparison.php
46