Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``reduce`` |
| 2 | ========== |
| 3 | |
| 4 | The ``reduce`` filter iteratively reduces a sequence or a mapping to a single |
| 5 | value using an arrow function, so as to reduce it to a single value. The arrow |
| 6 | function receives the return value of the previous iteration and the current |
| 7 | value of the sequence or mapping: |
| 8 | |
| 9 | .. code-block:: twig |
| 10 | |
| 11 | {% set numbers = [1, 2, 3] %} |
| 12 | |
| 13 | {{ numbers|reduce((carry, v) => carry + v) }} |
| 14 | {# output 6 #} |
| 15 | |
| 16 | The ``reduce`` filter takes an ``initial`` value as a second argument: |
| 17 | |
| 18 | .. code-block:: twig |
| 19 | |
| 20 | {{ numbers|reduce((carry, v) => carry + v, 10) }} |
| 21 | {# output 16 #} |
| 22 | |
| 23 | Note that the arrow function has access to the current context. |
| 24 | |
| 25 | Arguments |
| 26 | --------- |
| 27 | |
| 28 | * ``arrow``: The arrow function |
| 29 | * ``initial``: The initial value |