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
or
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)
Output: Example 2: Natural Sorting (Strings) Output: 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
sortfilter returns an empty array. - Non-Array Input: If the input is not an array, the
sortfilter returns the original input value unchanged. - Invalid Property: If the specified
property_namedoes 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
sortfilter 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.