Skip to content

sort

The 'sort' filter is designed to order the elements of an array. It can sort the elements based on their natural order (alphabetically or numerically) or by a specific property of the array elements.

Functionality

  • Arrays: Takes an array as input and returns a new array with the elements sorted.
  • Sorting Options:
    • Natural Sorting: Sorts the elements based on their natural order (alphabetically for strings, numerically for numbers).
    • Property-Based Sorting: Sorts the elements based on the value of a specified property of the objects within the array.

Syntax

    {{ array_variable | sort }} 

or

    {{ array_variable | sort: property_name }}
Arguments

  • property_name (optional): A string representing the name of the property to use for sorting the elements. If omitted, the filter performs natural sorting.

Code Samples

Example 1: Natural Sorting (Numbers)

    {% assign numbers = [5, 2, 8, 1] %}

    {{ numbers | sort }} 
Output:
[1, 2, 5, 8]
Example 2: Natural Sorting (Strings)

    {% assign fruits = ["banana", "apple", "orange"] %}

    {{ fruits | sort }} 
Output:
["apple", "banana", "orange"]
Example 3: Property-Based Sorting (Objects)
    {% assign products = [{ "name": "Product A", "price": 10 }, 
                          { "name": "Product B", "price": 25 }, 
                          { "name": "Product C", "price": 15 }] %}

    {{ products | sort: "price" }}

Output:

[{"name": "Product A", "price": 10}, {"name": "Product C", "price": 15}, {"name": "Product B", "price": 25}]

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the sort filter returns an empty array.
  • Non-Array Input: If the input is not an array, the sort filter returns the original input value unchanged.
  • Invalid Property: If the specified property_name does not exist on the elements of the array, the filter may return an error or unexpected results (depending on Experience Builder's error handling).

Key Points

  • The sort filter is essential for organizing and presenting data in a meaningful order within templates.
  • It offers flexibility to sort by natural order or by a specific property, making it adaptable to various use cases.
  • Pay attention to the data types of the elements being sorted, as natural sorting might behave differently for numbers and strings.