1

I'm trying to remove duplicate image objects from an array, but can't figure out why it won't find it:

{% for image in product.productGallery %}
    {% set productGalleryArray = productGalleryArray|merge([image]) %}
{% endfor %}

{% for variant in product.variants %}
    {% set variantImage = variant.productVariantImage.first() %}
    {% if variantImage|length and variantImage not in productGalleryArray %}
        {% set productGalleryArray = productGalleryArray|merge([variantImage]) %}
    {% endif %}
{% endfor %}

{% if productGalleryArray|length %}
    <div class="slideshow">
        {% for image in productGalleryArray %}
            <img src="{{ image.url }}" alt="{{ image.title }}">
        {% endfor %}
    </div>
{% endif %}

Essentially what I'm trying to do is have a productGallery field which you can add images to, but also add an image to the product variant via productVariantImage.

This can cause the issue where by theres duplicate of the same image being output from the slideshow after it's merged the two fields together.

So I need to ideally:

  • Remove the duplicates before the array is merged, OR
  • Find and remove duplicates after the array is merged (Via a Twig filter?)
1

I think you're checking correctly with {% if variantImage not in productGalleryArray %} (this should check if variantImage isn't already in the array), but your code doesn't seem to set a productGalleryArray array in the global scope. Variables initially set inside for loops are scoped only to that for loop.

So I think you just need to declare an empty array at the top of your code outside and before the first for loop:

{% set productGalleryArray = [] %}
| improve this answer | |
  • Sorry, I probably should have added this array to the question, as this is already in there. So I'm still having the issue :( – Jason Mayo Sep 25 '17 at 14:42

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.