group_by_exp

Groups an array using a Liquid expression to determine the group key. Unlike group_by, which groups by a direct property value, group_by_exp lets you write arbitrary expressions to compute the grouping key.

{% assign by_price_range = products | group_by_exp: "product", "product.price > 100" %}
{% for group in by_price_range %}
  {% log group.name | append: ": " | append: group.items.size | append: " products" %}
{% endfor %}

Syntax

{{ array | group_by_exp: item_name, expression }}
Parameter
Description

array

Array of objects to group

item_name

Variable name for the current item inside the expression

expression

Liquid expression that produces the group key

Return Value

Returns an array of group objects:

Property
Type
Description

name

any

The computed key value shared by all items in this group

items

Array

Array of items that produced this key value

Examples

Group products by price range:

{% assign by_range = products | group_by_exp: "p", "p.price > 50" %}
{% for group in by_range %}
  {% if group.name == true %}
    {% log "Premium products: " | append: group.items.size %}
  {% else %}
    {% log "Budget products: " | append: group.items.size %}
  {% endif %}
{% endfor %}

Group by first letter of title:

Group orders by fulfillment state:

Group by computed value using filters:

Output:

Group line items by quantity tier:

Notes

  • The item_name parameter defines how you reference each item inside the expression

  • The expression can use any Liquid filters and operators

  • The expression result becomes the group name — it can be a string, number, boolean, etc.

  • Groups are returned in the order their keys are first encountered

  • For simple property-based grouping, group_by is more concise

  • See also: group_by, group_by_property, group_by_fast

Last updated