I'm working with Shopify Liquid, and I need to sort an array of numbers in numerical order. However, the sort and sort_natural filters only seem to work alphabetically, which leads to issues when sorting numeric values.
For example, when I have the following array of numbers:
{% assign numbers = '10,2,30,5,1' | split: ',' %}
Using the sort or sort_natural filters:
{% assign sorted_numbers = numbers | sort %}
Results in this output:
1,10,2,30,5
As you can see, it’s sorting them alphabetically, not numerically. What I need is:
1,2,5,10,30
My question is: How can I sort this array of numbers numerically in Shopify Liquid?
Any help or guidance on how to work around this limitation in Liquid would be greatly appreciated!
I'm working with Shopify Liquid, and I need to sort an array of numbers in numerical order. However, the sort and sort_natural filters only seem to work alphabetically, which leads to issues when sorting numeric values.
For example, when I have the following array of numbers:
{% assign numbers = '10,2,30,5,1' | split: ',' %}
Using the sort or sort_natural filters:
{% assign sorted_numbers = numbers | sort %}
Results in this output:
1,10,2,30,5
As you can see, it’s sorting them alphabetically, not numerically. What I need is:
1,2,5,10,30
My question is: How can I sort this array of numbers numerically in Shopify Liquid?
Any help or guidance on how to work around this limitation in Liquid would be greatly appreciated!
Share Improve this question asked Mar 11 at 9:51 albertosetimalbertosetim 191 silver badge7 bronze badges1 Answer
Reset to default 0A similar question was asked here.
https://community.shopify/c/shopify-design/sorting-number-in-natural-order-in-collections/m-p/1850181
Since the values are likely being treated as strings the order isn't based on numeric values (but string values).
This is verbose code I've just smashed out that for production would need to be cleaned up, added whitespace control and made more efficient - but should be easier to read for this thread.
{% assign myArray = "11,7,4,3,12,9,2,8,6,10,1,5" | split:"," %} {% assign myNewArray = "" %} {% assign zeroFill = "00000000" %} {% for i in myArray %} {% assign thisFill = zeroFill | slice:i.size, zeroFill.size %} {% assign newValue = thisFill | append:i | append:"," %} {% assign myNewArray = myNewArray | append:newValue %} {% endfor %} {% assign myNewArray = myNewArray| split:"," | sort %} {% for i in myNewArray %} {{ i | abs }}<br /> {% endfor %}
Does that help?
I also touch on something similar here.
https://freakdesign.au/blogs/news/sort-products-in-a-shopify-collection-by-metafield-value-without-javascript
He adds zeros to each number in order to work around the issue.