2

Anyone able to assist me with removing duplicates in this example? So I have a related entries (cables) setup in a SuperTable. Some of these entries are duplicated across different rows. So a cable might be related to the first row in the SuperTable and also row3 and row4.

I want to be able to run through all these cables in any SuperTable row and output the entries just once not duplicated. So as an example a basic SuperTable setup like this;

{% for row in entry.tests %}
    {% for cable in row.cables %}
        {{ cable.title }}<br />
    {% endfor %}
{% endfor %}

would output this;
BS 7211
BS EN 50525
BS 6724
BS 8573
BS 7835
BS 7629-1
BS 8436
BS 5467
BS 6724
BS 7846
BS 6622
BS 7835

I want to essentially loop through and only display the related entry once. As you can see from the example some entries are duplicated (e.g BS 6724)

2

The simplest way is to create a "filtered" array, containing the unique cables, and then loop through that.

For example:

{# Build the "filtered" array of cables #}
{% set filteredCables = [] %}

{% for row in entry.tests %}
    {% for cable in row.cables %}
        {% if cable.title not in filteredCables %}
            {% set filteredCables = filteredCables|merge([cable.title]) %}
        {% endif %}
    {% endfor %}
{% endfor %}

{# Output the unique cables #}
{% for cable in filteredCables %}
    {{ cable }}<br />
{% endfor %}
| improve this answer | |
  • Thanks for this @StephenLewis - I had actually tried this as I picked it up from another stack exchange post. However, I keep hitting them same error; Variable "filteredCables" does not exist. I have tried to set the {% set filteredCables = [] %} before I then set it in the loop but it still seems to output all the cables (duplicates) and not a filtered list. Any ideas? – Terry Upton Mar 21 '17 at 16:34
  • Regarding the variable does not exist error, you could do this: {% set filteredCables = filteredCables|default([])merge([cable]) %}. As for it not outputting a filtered list, have you tried just adding the titles? For example: {% if cable.title not in filteredCables %}{% set filteredCables = filteredCables|default([])|merge([cable]) %}{% endif %} – Stephen Lewis Mar 21 '17 at 16:37
  • Thanks Stephen - the problem was solved by setting cable.title. I had to add an empty variable at the start outside the loop too {% set filteredCables = [] %}. Thanks for putting me in the right direction. – Terry Upton Mar 21 '17 at 17:17
  • Glad you got it sorted. I've updated the answer to use the cable title. – Stephen Lewis Mar 21 '17 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.