2026 Community Survey results are here! See how the Craft CMS community works. results are live!

Reduce Filter and Arrow Functions in Twig

Examples of using the reduce filter in Twig.

Using the same data that is includ­ed in the pre­vi­ous video, Andrew shows how to use the reduce fil­ter in Twig. 

To demon­strate how to use the reduce fil­ter, Andrew seeks to find the total val­ue of all of the items in the data set.

Find Total Val­ue Using a Loop

We’ll start by imple­ment­ing 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 %}

Find Total Val­ue Using reduce

We know that reduce is a bet­ter way to tal­ly up the val­ues of the items in the data set. We drop the loop and imple­ment the reduce filter. 

    {% set totalValue = ryansGoBag | reduce(
        (carry, item) => carry + item.value * (conversionRates[item.name] ?? 1.0),
        0
        )
        | currency('USD') %}

    {% dd totalValue %}

Find Total Val­ue Using reduce and Craft Closure

We keep the reduce fil­ter but add an arrow vari­able using Craft Clo­sure. Pret­ty sweet!

    {% set totalAmountArrow = (carry, item) => carry + item.value * (conversionRates[item.name] ?? 1.0) %}
    {% set totalValue = ryansGoBag | reduce(totalAmountArrow, 0) | currency('USD') %}

    {% dd totalValue %}

Anoth­er use of the reduce fil­ter is to get a list of the types of items in the data set. How­ev­er, we only want a type list­ed once, not mul­ti­ple times.

Get Types of Items Using Loop

    {% set types = [] %}
    {% for item in ryansGoBag %}
        {% if item.type not in types %}
            {% set types = types | merge([item.type]) %}
        {% endif %}
    {% endfor %}

    {% dd types %}

Get Types of Items Using reduce

In this exam­ple, we drop the for-loop and replace it with a reduce fil­ter using an arrow function.

    {% set types = ryansGoBag | reduce(
        (carry, item) => item.type in carry ? carry : carry | merge([item.type]),
        []
        ) %}

    {% dd types %}

Get Types of Items Using reduce and Craft Closure

Final­ly, we use reduce, an arrow func­tion with an arrow vari­able avail­able 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 %}
Craft Version
Craft 4
Topic
Instructor
Andrew Welch
Level
Intermediate
Date Published
August 22, 2022
Andrew Welch

Andrew is a regular contributor to CraftQuest through the CraftQuest on Call livestream. He's the developer behind the most popular Craft CMS plugins, like SEOmatic and Retour. Andrew has decades of experience in software development for both web and client applications.