Sorting Number in Natural Order in Collections

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

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  }}

{%  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-without-javascript

1 Like

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

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.

I found a workaround solution… Edit the collection and change the Sort to “Manually”, then you can organize the list however you want. It’s extra work, but it gets the job done.

1 Like

Thank you so much! It’s work, but nothing like going in and changing every number and having it not what a customer searches for! Your awesome!