Merge two arrays of ElementModels? I have two queries on related entries (using Many to Many plugin) to find both related and then reverse related entries:



{% set relatedArticles = article.relatedArticles %}

{% set reverseRelatedArticles = craft.entries.relatedTo(article) %}`


I want to merge these two ElementCriteriaModel, removing any duplicates before processing them further. I've tried this:

{% for item in reverseRelatedArticles %}
    {% if item not in relatedArticles %}
        {% set relatedArticles = relatedArticles|merge([item]) %}
    {% endif %}
{% endfor %}


But it doesn't remove the duplicates. Adding find() to the queries to turn them in to an array doesn't work either. Any way I can do this?

EDIT: I tried this, too:

{% set relatedArticles = article.relatedArticles.find()|merge(craft.entries.relatedTo(article).find()) %}
Yep, there's a great mystery about how the in containment operator actually works with objects. Twig Docs say it's possible:


  You can use this filter to perform a containment test on strings, arrays, or objects implementing the Traversable interface.


but I also tried this (multiple times) and did't get it working. I eventually always ended up using a workaround. In your case I'd do the following and use the entry's ID in the conditional:

{# Get arrays of entries #}
{% set entriesA = craft.entries(paramsA).find() %}
{% set entriesB = craft.entries(paramsB).find() %}

{# Prepare merge #}
{% set entriesBIds = craft.entries(paramsB).ids() %}
{% set allEntries = entriesB %}

{# Merge arrays #}
{% for entry in entriesA %}

    {# Don't merge duplicates #}
    {% if entry.id not in entriesBIds %}
        {% set allEntries = allEntries|merge([entry]) %}
    {% endif %}

{% endfor %}