Checking for duplicates in array 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 %}
    &lt;div class="slideshow"&gt;
        {% for image in productGalleryArray %}
            &lt;img src="{{ image.url }}" alt="{{ image.title }}"&gt;
        {% endfor %}
    &lt;/div&gt;
{% 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?)
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 = [] %}