Ad

Liquid - Sort Array Of Based On Separate Array

- 1 answer

I'm looking for a way to filter and sort an array of images based on a separate array.

The images:

{% assign images = '
100-0000-BLK-LF01.jpg,
100-0000-BLK-L01.jpg,
100-0000-BLK-T01.jpg,
100-0000-BLK-S01.jpg,
100-0000-BLK-HF01.jpg,
100-0000-BLK-F01.jpg' | strip | split: ',' %}

The sort array:

{% assign codes_360 = '-F01,-L01,-S01,-U01,-B01,-T01' | split: ',' %}

I can filter out the images based on the codes, but then need them sorted according to the codes array:

{%- capture images_360 -%}
{%- for image in images -%}
  {%- for code in codes_360 -%}
    {%- if image contains code -%}
      {{- image -}}{%- if forloop.last == false -%}::{%- endif -%}
    {%- endif -%}    
  {%- endfor -%}
{%- endfor -%}
{%- endcapture -%}
{%- assign images_360 = images_360 | strip | split: '::' -%}
{{ images_360 }}

Outputs:

100-0000-BLK-L01.jpg
100-0000-BLK-T01.jpg
100-0000-BLK-S01.jpg
100-0000-BLK-F01.jpg

I'd like to have them sorted according to the codes_360 array:

100-0000-BLK-F01.jpg
100-0000-BLK-L01.jpg
100-0000-BLK-S01.jpg
100-0000-BLK-T01.jpg
Ad

Answer

Figured it out by switching the order of the outer forloop and nested forloop. Then adding a reference to the outer forloop in order to check if the index (0,1,2,3) is equal to the corresponding value in in the sorting array.

{% assign codes_360 = '-F01,-L01,-S01,-U01,-B01,-T01' | split: ',' %}
{% assign images = '
BLK-LF01.jpg,
BLK-L01.jpg,
BLK-T01.jpg,
BLK-S01.jpg,
BLK-HF01.jpg,
BLK-F01.jpg' | split: ',' %}
{%- capture images_360 -%}
{%- for code in codes_360 -%}
  {% assign code_forloop = forloop %}
  {%- for image in images -%}
    {%- if image contains code and codes_360[code_forloop.index0] == code -%}
      {{- image -}}{%- if forloop.last == false -%}::{%- endif -%}
    {%- endif -%}    
  {%- endfor -%}
{%- endfor -%}
{%- endcapture -%}
{%- assign images_360 = images_360 | strip | split: '::' -%}
{{ images_360 }}

Outputs:

BLK-F01.jpg
BLK-L01.jpg
BLK-S01.jpg
BLK-T01.jpg
Ad
source: stackoverflow.com
Ad