簡體   English   中英

使用液體過濾器使數組元素小寫以進行排序

[英]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:缺少什么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 到 integer 的隱式轉換

我提出問題后添加了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: "-" }}

將輸出AbCdE

US(單位分隔符\\ u001F ,而不是\␟RS(記錄分隔符\ ,而不是\␞是兩個不太可能出現在輸入中的字符,因此它們在大多數情況下都可以安全使用。 他們可能是,| 例如,如果您想對 CSS ID 進行排序。

sort_natural過濾器執行不區分大小寫的排序:

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

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

輸出giraffe, octopus, Sally Snake, zebra

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM