Display list of results minus duplicates in Liquid

2.8k views Asked by At

I have a string field called Industry where people will be entering in their Industries. e.g. Agriculture, Manufacturing, IT, Landscaping etc.

I would like to output this data using liquid however, I want to place it into an Web App Search form within a dropdown menu so users can search for the particular field. Therefore I would not like to add any items that are duplicates.

E.g. entries from users include: Agriculture, Manufacturing, Agriculture, IT, Landscaping, Agriculture - you can see Agriculture is used 3 times. If i use the below it will be listed 3 times:

<select>
{module_webapps id="12345" collection="industry" filter="all" template=""}
{% for item in industry.items %}
     <option value="{{item.industry}}">{{item.industry}}</option>
{% endfor %}
</select>

How do I use a loop or an array to only display the industry once and hide all other duplicates?

Thanks

1

There are 1 answers

0
jrbedard On

You can capture a string of all your items. Then use the string filter split to convert it into an array, based on a delimiter. Then use the uniq array filter to remove all the duplicates. Finally, iterate the resulting array to build your dropdown menu.

<select>
{module_webapps id="12345" collection="industry" filter="all" template=""}

{% capture items %}
{% for item in industry.items %}
{{item.industry}},
{% endfor %}
{% endcapture %}

{% for item in items | split: ',' | uniq %}
    <option value="{{item}}">{{item}}</option>
{% endfor %}
</select>