Uniq filter not working

New Member
2 0 0

Hi, 

I'm trying to group an array by unique values. For example, there are multiple variants where option1: "black." The Uniq filter is not grouping the 'colors' array below. Whats wrong with my code?

 

  {% for variant in product.variants %}
    {% assign colors = variant.option1  %}
       <option>
         {{ colors | uniq }}
       </option>
  {% endfor %}

 

0 Likes
Shopify Expert
9418 9 1258

There's nothing wrong with your code - though there's nothing wrong with the uniq filter either. 

You are looping over each variant one at a time and during that loop you are assigning the value of variant.option1 in to the variable called colors. That value isn't an array so calling uniq won't do anything for you here, since it's already a single value.

I'm not sure what you are hoping to achieve so there'd likely need to be a reconsideration of what code you're using. What are you trying to do?

★ Winning Partner of the Build a Business competition. ★ http://freakdesign.com.au
0 Likes
New Member
2 0 0

I guess the issue is that it's not an array. I'm trying to output all the color options for a product in a select menu. https://ibb.co/n10GLa

Right now it outputs them one for each variant:

https://ibb.co/hnygmF

Surely there's an easier way?

0 Likes
Highlighted
Astronaut
1925 0 352

You can use the code below to get an array of all the unique options (for option1).  But it looks like you want to create an option selector.  You may need to approach this from a completely different angle.

  {% assign colors = product.variants | map:'option1' | uniq %}
  {% for color in colors %}
       <option>
         {{ color }}
       </option>
  {% endfor %}

 

2 Likes