Examples of using the reduce filter in Twig.
Using the same data that is included in the previous video, Andrew shows how to use the reduce
filter in Twig.
To demonstrate how to use the reduce
filter, Andrew seeks to find the total value of all of the items in the data set.
We’ll start by implementing it with a loop:
{% set totalValue = 0 %}
{% for item in ryansGoBag %}
{% set totalValue = totalValue + item.value * (conversionRates[item.name] ?? 1.0) %}
{% endfor %}
{% set totalValue = totalValue | currency('USD') %}
{% dd totalValue %}
reduce
We know that reduce
is a better way to tally up the values of the items in the data set. We drop the loop and implement the reduce
filter.
{% set totalValue = ryansGoBag | reduce(
(carry, item) => carry + item.value * (conversionRates[item.name] ?? 1.0),
0
)
| currency('USD') %}
{% dd totalValue %}
reduce
and Craft ClosureWe keep the reduce
filter but add an arrow variable using Craft Closure. Pretty sweet!
{% set totalAmountArrow = (carry, item) => carry + item.value * (conversionRates[item.name] ?? 1.0) %}
{% set totalValue = ryansGoBag | reduce(totalAmountArrow, 0) | currency('USD') %}
{% dd totalValue %}
Another use of the reduce
filter is to get a list of the types of items in the data set. However, we only want a type listed once, not multiple times.
{% set types = [] %}
{% for item in ryansGoBag %}
{% if item.type not in types %}
{% set types = types | merge([item.type]) %}
{% endif %}
{% endfor %}
{% dd types %}
reduce
In this example, we drop the for-loop and replace it with a reduce
filter using an arrow function.
{% set types = ryansGoBag | reduce(
(carry, item) => item.type in carry ? carry : carry | merge([item.type]),
[]
) %}
{% dd types %}
reduce
and Craft ClosureFinally, we use reduce
, an arrow function with an arrow variable available to us via Craft Closure:
{% set typesArrow = (carry, item) => item.type in carry ? carry : carry | merge([item.type]) %}
{% set types = ryansGoBag | reduce(typesArrow, []) %}
{% dd types %}
Arrow Functions in Twig is made up of the following videos: