I’m stuck on a Shopify Liquid problem. I’ve got a bunch of numbers in an array, but I can’t get them to sort right. The usual sort filters are messing things up.
Here’s what I mean:
{% assign my_nums = '8,15,3,42,1' | split: ',' %}
{% assign sorted_nums = my_nums | sort %}
This gives me:
1,15,3,42,8
But I need:
1,3,8,15,42
Is there a trick to make Liquid sort numbers properly? The alphabetical sorting just isn’t cutting it. Any ideas on how to fix this would be awesome!
I’ve encountered this issue before, and there’s a workaround that might help. Liquid’s default sort treats everything as strings, which explains the unexpected order. Here’s a trick I’ve used:
Try padding your numbers with leading zeros to a fixed width. For example:
{% assign my_nums = '8,15,3,42,1' | split: ',' %}
{% assign padded_nums = my_nums | map: 'to_i' | map: 'prepend', '000' | map: 'slice', -3, 3 %}
{% assign sorted_nums = padded_nums | sort %}
This converts each number to an integer, pads it with zeros, then takes the last three digits. The result should be correctly sorted numerically. You might need to adjust the padding based on your largest expected number.
After sorting, you can remove the padding if needed. It’s not the most elegant solution, but it gets the job done in Liquid’s limitations.
hey there! i ran into this same headache. what worked for me was using the ‘plus’ filter to force numeric comparison. try this:
{% assign sorted_nums = my_nums | sort_natural | map: ‘plus:0’ %}
it converts everything to numbers. hope that helps ya out!