You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shopify Liquid中对数字数组进行数值排序?

Shopify Liquid 数字数组数值排序方案

Liquid 的 sort 和 sort_natural 过滤器默认按字符串Unicode顺序排序,直接对 split 生成的数字字符串数组排序会得到非预期结果。要实现数值排序,需先将元素转为数值类型,再通过循环手动实现排序逻辑,以下是可行方案:

代码实现

{% assign numbers = '10,2,30,5,1' | split: ',' %}
{% assign sorted_numbers = '' %}

{% for current_num in numbers %}
  {% assign current_val = current_num | plus: 0 %}
  {% assign is_inserted = false %}
  {% assign temp_sorted = sorted_numbers | split: ',' %}

  {% if temp_sorted.size == 0 %}
    {% assign sorted_numbers = current_num %}
    {% continue %}
  {% endif %}

  {% for sorted_item in temp_sorted %}
    {% assign sorted_val = sorted_item | plus: 0 %}
    {% if current_val < sorted_val %}
      {% capture before %}{{ temp_sorted | slice: 0, forloop.index0 | join: ',' }}{% endcapture %}
      {% capture after %}{{ temp_sorted | slice: forloop.index0, temp_sorted.size | join: ',' }}{% endcapture %}
      {% assign temp_sorted = '' %}
      {% if before != '' %}{% assign temp_sorted = before | append: ',' %}{% endif %}
      {% assign temp_sorted = temp_sorted | append: current_num %}
      {% if after != '' %}{% assign temp_sorted = temp_sorted | append: ',' | append: after %}{% endif %}
      {% assign sorted_numbers = temp_sorted %}
      {% assign is_inserted = true %}
      {% break %}
    {% endif %}
  {% endfor %}

  {% unless is_inserted %}
    {% assign sorted_numbers = sorted_numbers | append: ',' | append: current_num %}
  {% endunless %}
{% endfor %}

{{ sorted_numbers }}

逻辑说明

  1. 将原始字符串分割为字符串数组,初始化空字符串存储排序结果
  2. 遍历每个待排序元素,用 plus: 0 将字符串转为数值类型,确保比较时按数值大小判断
  3. 遍历已排序的临时数组,找到当前元素的插入位置:
    • 若当前元素数值小于遍历到的已排序元素,将其插入到该位置之前
    • 若遍历完所有已排序元素仍未找到插入位置,将当前元素追加到数组末尾
  4. 最终 sorted_numbers 即为按数值从小到大排序的结果

输出结果

运行代码后输出:

1,2,5,10,30

内容的提问来源于stack exchange,提问作者albertosetim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:13:11