Search code examples
jekyllliquid

Is there a way to remove duplicates in a multi dimensional array in Liquid


I know that you can use the uniq filter in liquid but this seems to flatten the array which is not what I want.

Here's an example of my array:

[
  ["Brazil", "/assets/images/flags/brazil.png"], 
  ["Brazil", "/assets/images/flags/brazil.png"],
  ["Argentina", "/assets/images/flags/argentina.png"]
]

If I reassign the array with the uniq filter as below I get the following results:

{% assign countries = countries | uniq %}

Array becomes:

["Brazil", "/assets/images/flags/brazil.png", "Brazil", "/assets/images/flags/brazil.png", "Argentina", "/assets/images/flags/argentina.png"]

How can I remove the duplicate and keep the current structure of my array?


Solution

  • I ended up solving this with the following liquid:

    {% assign contacts = include.contacts %}
    {% assign countries = '' | split: '' %}
    {% for item in contacts %}
        {% assign array_item = '' | split: '' %}
        {% assign array_item = array_item | push: item.country %}
        {% assign array_item = array_item | push: item.country_flag_image %}
    
        {% unless countries contains array_item %}
            {% assign countries = countries | push: array_item %}
        {% endunless %}
    {% endfor %}
    

    For each iteration within the for loop I create a new array object which contains both the country, and flag image as array items. Before adding this new array to the countries array I check whether it already exists with the unless statement. If it doesn't exist it gets added to the countries array.

    If there's a better solution please let me know