AVADA logo
Published on

How to Sort items of Array by Given Attribute in Liquid in Shopify

489 words3 min read
  • Name

You want to find a product but this product is in a pool of related items, hence you would like to sort items of an array. Don’t worry, follow these steps below. The tutorial will help you classify items of array by given attribute in liquid

Table of content

What is Liquid template language?

Refering to Shopify's template language, Liquid is the popular one which is used by a lot of website developers. Liquid is used as the backbone of Shopify to upload dynamic content on the front page. Liquid has been sold since 2006 and now become a good source for a lot of hosted website application such as Jekyll, salesforce desk, and zendesk.

What is array filter?

Filter is a useful function when you use Liquid on Shopify platform. Filter feature offers callback function for each character in an array and build a new array that can also give the value back to confirm the true feature of that element. Callback is available with three arguments: the value of element, the index of element and the array objects.

In addition, the range of elements demonstrated by filter is set by the first petition of callback. If existing elements are changed or eliminated, their value will be passed to the filter hence when filter check these elements, their value is remained.

Liquid code can be classified into three different categories: objects, tags and filters. Objects annouce Liquid where to show content on a page. Objects and variable names are denoted by double curly braces { and }}. The main function of tags is to control the flow of the template. Tags are presented by one curly brace and a percent sign {% and %}. Filters are used to change the output of a Liquid object and seperated by a straight flash |.

Moreover, you can show products_array elsewhere on the page. Therefore, it can be said that Liquid is a flexible language.

The function of sorting items is to classify elements by an assigned attribute of an array.

How to sort items of array by given attribute in liquid

Look at this example:


{% assign products = collection.products | sort: 'price' %}
{% for product in products %}
  <h4>{{ product.title }}</h4>
{% endfor %}

An advanced case is provided like your reference: Input:

<!-- products = "a", "b", "A", "B" -->
{% assign products = collection.products | sort: 'title' %}
{% for product in products %}
   {{ product.title }}
{% endfor %}


A B a b


In conclusion, sorting items of an array may make the shopping journey become easier. Buyers will find it more convenient when shopping around because they do not need much time to seek key tags or information.