使用 Liquid 过滤器使数组元素小写以进行排序

Make array elements lowercase with Liquid filters for sorting

我不知道如何不区分大小写地对包含字符串的数组进行排序: ["A", "C", "E", "b", "d"] 变成 ["A", "b", "C", "d", "E"].

{% assign input = "A,C,E,b,d" | split:"," %}
{{ input | join: "-" }}
{{ input | map: 'downcase' | join: "-" }}
{{ input | map: 'downcase' | sort | join: "-" }}
{{ input | map: 'length' | join: "-" }}
{{ input | map: 'size' | join: "-" }}

map: 我错过了什么?

预期输出:

A-C-E-b-d
a-c-e-b-d
a-b-c-d-e
1-1-1-1-1
1-1-1-1-1

实际输出:

A-C-E-b-d
----
----
----
----

注意:起初我尝试了 map: downcase(不带引号),但是 没有从 nil 到整数的隐式转换

sort_natural是我问完后加的。请参阅 答案。我会把这个答案留在这里,因为它显示了如何按任意键进行排序。

{% assign input = "A,C,E,b,d" | split:"," %}
{% capture intermediate %}{% for entry in input %}{{ entry | downcase }}{{ entry }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign intermediate_sorted = intermediate | split:'' | sort %}
{% capture sorted %}{% for entry in intermediate_sorted %}{{ entry | split: '' | last }}{% unless forloop.last %}{% endunless %}{% endfor %}{% endcapture %}
{% assign sorted = sorted | split: '' %}
{{ sorted | join: "-" }}

会输出A-b-C-d-E.

US (Unit Separator, \u001F, not \u241F) and RS (Record Separator, \u001E, not \u241E)是输入中不太可能出现的两个字符,所以大部分时候可以放心使用。例如,如果您想对 CSS 个 ID 进行排序,它们可以是 ,|

sort_natural filter 进行不区分大小写的排序:

{% assign my_array = "zebra, octopus, giraffe, Sally Snake" | split: ", " %}

{{ my_array | sort_natural | join: ", " }}

输出giraffe, octopus, Sally Snake, zebra