Solved

How can I sort a nested array by product type?

kampotix
Visitor
2 0 0

Here's my code:

 

 

{% for line_item in line_items | sort: "line_item.product.type" %}
      <tr>
        <td>{{ line_item.quantity }} x</td>
        <td><b>{{ line_item.title }}</b></td>
        {% if show_line_item_taxes %}
        <td>
          {% for tax_line in line_item.tax_lines %}
            {{ tax_line.price | money }} {{ tax_line.title }}<br/>
          {% endfor %}
        </td>
        {% endif %}
        <td>
          {% if line_item.original_price != line_item.price %}
            <s>{{ line_item.original_price | money }}</s>
          {% endif %}
          {{ line_item.price | money }}
        </td>
        <td>{{ line_item.product.type }}</td>
      </tr>
    {% endfor %}

 

 

sort.jpg

 

I need to sort by product type (Category). Thank you.

Accepted Solution (1)

MaxDesign
Shopify Expert
213 15 83

This is an accepted solution.

Hi there,

You can try something along these lines, it should accomplish what you want. It's not pretty but not ugly either, I'm also curious to know if there's a way to filter/sort nested properties more efficiently, but Im' not aware of it :

 

 

{% assign line_items = cart.items %}
{% assign types = line_items | map: 'product' | map: 'type' | sort_natural | uniq %}
{% for type in types %}
  {% for line_item in line_items %}
    {% if line_item.product.type == type %}
      your code...
    {%  endif %}
{% endfor %}
{% endfor %}

 

So basically, I take the problem differently. I first make a list of all product types in the cart, sort them alphabetically, and remove the duplicate types. We loop through each type, and then loop through each line_item inside of that, which allow us to filter out line_items types that are not matching the type from the main loop.

Cheers

Reach out to me at admin@maxdesign.expert

View solution in original post

Replies 2 (2)

MaxDesign
Shopify Expert
213 15 83

This is an accepted solution.

Hi there,

You can try something along these lines, it should accomplish what you want. It's not pretty but not ugly either, I'm also curious to know if there's a way to filter/sort nested properties more efficiently, but Im' not aware of it :

 

 

{% assign line_items = cart.items %}
{% assign types = line_items | map: 'product' | map: 'type' | sort_natural | uniq %}
{% for type in types %}
  {% for line_item in line_items %}
    {% if line_item.product.type == type %}
      your code...
    {%  endif %}
{% endfor %}
{% endfor %}

 

So basically, I take the problem differently. I first make a list of all product types in the cart, sort them alphabetically, and remove the duplicate types. We loop through each type, and then loop through each line_item inside of that, which allow us to filter out line_items types that are not matching the type from the main loop.

Cheers

Reach out to me at admin@maxdesign.expert
kampotix
Visitor
2 0 0

It works, thank you very much!