跳到主要内容

数组过滤器

Array filters 用于修改数组

concat

array | concat: array

将两个数组拼接(合并)在一起。

📘 注意

concat filter 不会过滤重复项。如果需要删除重复项,请使用 uniq filter

{% assign cold_climate_fruits = 'Apple,Pear' | split: ',' %}
{% assign warm_climate_fruits = 'Dragon fruit,Mango' | split: ',' %}
{% assign all_fruits = cold_climate_fruits | concat: warm_climate_fruits %}

{% for fruit in all_fruits %}
{{ fruit }}
{% endfor %}
Apple
Pear
Dragon fruit
Mango

first

array | first

返回数组中的第一个元素。

{% assign first_product = collection.products | first %}

{{ first_product.title }}
{
"collection": {
"products": [
{
"title": "Fit 3 Denim Shirt"
},
{
"title": "Ace Cashmere Beanie"
}
]
}
}
Fit 3 Denim Shirt

join

array | join
returns  string

将数组中的所有元素合并为单个字符串,以空格分隔。

{{ collection.tags | join }}
{
"collection": {
"tags": [
"cold",
"fresh",
"large"
]
}
}
cold fresh large

自定义分隔符

array | join: string

您可以为合并的元素指定自定义分隔符。

{{ collection.tags | join: ', ' }}
{
"collection": {
"tags": [
"cold",
"fresh",
"large"
]
}
}
cold, fresh, large

last

array | last

返回数组中的最后一个元素。

{% assign last_product = collection.products | last %}

{{ last_product.title }}
{
"collection": {
"products": [
{
"title": "Fit 3 Denim Shirt"
},
{
"title": "Ace Cashmere Beanie"
}
]
}
}
Ace Cashmere Beanie

map

array | map: string

从数组中各元素的特定属性创建一个新数组。

{% assign product_titles = collection.products | map: 'title' %}

{{ product_titles | join: '@' }}
{
"collection": {
"products": [
{
"title": "Fit 3 Denim Shirt"
},
{
"title": "Ace Cashmere Beanie"
}
]
}
}
Fit 3 Denim Shirt@Ace Cashmere Beanie

reverse

array | reverse

反转数组中元素的顺序。

Original order:
{{ collection.products | map: 'title' | join: '@' }}

Reverse order:
{{ collection.products | reverse | map: 'title' | join: '@' }}
{
"collection": {
"products": [
{
"title": "Fit 3 Denim Shirt"
},
{
"title": "Ace Cashmere Beanie"
}
]
}
}
Original order:
Fit 3 Denim Shirt@Ace Cashmere Beanie

Reverse order:
Ace Cashmere Beanie@Fit 3 Denim Shirt

size

variable | size
returns  number

返回字符串或数组的大小。

字符串的大小为其包含的字符数,数组的大小为其元素个数。

{{ collection.title | size }}
{{ collection.products | size }}
17
2

sort

array | sort

按区分大小写的字母顺序或数值顺序对数组中的元素进行排序。

{% assign tags = collection.tags | sort %}

{% for tag in tags %}
{{ tag }}
{% endfor %}
{
"collection": {
"tags": [
"Burning",
"fresh",
"music",
"plant",
"Salty"
]
}
}

Burning
Salty
fresh
music
plant

按数组元素属性排序

array | sort: string

您可以指定数组元素的某个属性作为排序依据,可以按正在排序的 object 的任意属性进行排序。

{% assign products = collection.products | sort: 'price' %}

{% for product in products %}
{{ product.title }}
{% endfor %}
{
"collection": {
"products": [
{
"title": "Fit 3 Denim Shirt",
"price": "22.00"
},
{
"title": "Ace Cashmere Beanie",
"price": "12.88"
}
]
}
}
Ace Cashmere Beanie
Fit 3 Denim Shirt

uniq

array | uniq

删除数组中的重复元素。

{% assign random_number = '2,2,3,3,4' | split: ',' %}

{{ random_number | uniq | join: ',' }}
2,3,4