index_by

Creates a lookup object from an array, indexed by a specified property. This enables O(1) direct access to items instead of O(n) array searching with where or find.

{% assign products_by_sku = products | index_by: "sku" %}

{% comment %} O(1) direct access instead of O(n) search {% endcomment %}
{% assign product = products_by_sku["ABC123"] %}

Syntax

{{ array | index_by: property }}
{{ array | index_by: "nested.property" }}
Parameter
Description

array

Array of objects to index

property

Property name to use as the index key (supports dot notation for nested properties)

Variants

index_by

Returns an object where each key maps to a single item. If multiple items share the same key, the last one wins.

{% assign users_by_email = users | index_by: "email" %}
{% assign user = users_by_email["[email protected]"] %}

index_by_all

Returns an object where each key maps to an array of all items with that key. Useful when multiple items can share the same key.

{% assign orders_by_status = orders | index_by_all: "status" %}
{% assign pending_orders = orders_by_status["pending"] %}
{% log "Pending orders: " | append: pending_orders.size %}

Examples

Fast variant lookup by SKU:

Index GraphQL edges by nested property:

Group orders by customer for batch processing:

Match inventory levels to variants:

Create lookup for metafield values:

Performance Comparison

Operation
Without index_by
With index_by

Build index

-

O(n) once

Single lookup

O(n) with where

O(1)

100 lookups

O(n × 100)

O(n) + O(100)

1000 lookups

O(n × 1000)

O(n) + O(1000)

For an array of 10,000 items with 500 lookups:

  • Without index: 10,000 × 500 = 5,000,000 operations

  • With index: 10,000 + 500 = 10,500 operations

Notes

  • Supports nested properties using dot notation: "node.sku", "variant.barcode"

  • Returns empty object {} for null, undefined, or non-array input

  • Items with null or undefined key values are skipped

  • For index_by: if multiple items have the same key, the last item is kept

  • For index_by_all: all items with the same key are collected into an array

Last updated