Hi, I’m trying to reverse the order of when a product is added to the cart. Basically just taking the current sorting and reversing it (want the last item added to be on the bottom). I did try reversing the items first {%- assign sorted_cart_items = cart.items | reverse -%} but the forloop.index goes off track. So if I try to delete the last item on the sorted list, it deletes the first item.
Is there a way to sort the array by date added that does not use the array filter reverse?
To my knowledge, liquid does not have a way to sort an array by a property such as the date added to cart.
The cart.items array in Shopify Liquid is automatically sorted in the order that items are added, with the most recently added item first. This is why you are finding that reversing the array appears to sort it in the order you want, but then other functions like forloop.index don’t work as expected.
One workaround for your use case might be to keep track of the original index of each cart item, and use that for deletion:
{%- assign sorted_cart_items = cart.items | reverse -%}
{%- for item in sorted_cart_items -%}
{%- assign original_index = cart.items.size | minus: forloop.index -%}
Remove
{%- endfor -%}
This way, when you reverse the array, you’re still keeping track of the original index (1-indexed, not 0-indexed as in some languages) of each item in the cart.items array. When you link to /cart/change?line={{ original_index }}&quantity=0, it will delete the item at that original index in the cart, which should match the user’s expectation based on the order you’ve displayed the items.
Remember that this workaround only works because the original cart.items array is maintained in the order items were added. If Shopify ever changes that behavior, this code could stop working as expected.