New Shopify Certification now available: Liquid Storefronts for Theme Developers

Sorting Number in Natural Order in Collections

knowherecomics
Excursionist
16 0 3

Does anyone know if there is a way to edit the code to sort numbers in natural order?

It should be 1,2,3...10,11,12 etc but shopify will sort it as 10, 11 12, 1, 20 21, 2 etc.. it's really annoying?

 

I know I can use 001 002 etc instead but that's quite cumbersome and I have over 50,000 products.

 

Thanks

Replies 3 (3)
Jason
Shopify Expert
11159 222 2274

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.com.au/blogs/news/sort-products-in-a-shopify-collection-by-metafield-value-witho...

 

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★
EdLazor
Excursionist
14 0 3

Did you come up with a good solution for this?  I also have products with the number in the title.

sweetstash
Excursionist
53 0 7

I too need this.  Right now my products sort a-z like this  1, 10, 101, 2, 22, 224, 3, 324, 3246, 330, 3374, 4...

I need it to sort like 1, 2, 3, 4, 10, 22, 101, 224, 324, 330, 3246...  WITHOUT adding zeros to make all numbers 4 digits long.