Skip to content

sort_natural

The 'sort_natural' filter is designed to order the elements of an array in a way that mimics human intuition for sorting mixed alphanumeric data.

Functionality

  • Arrays: Takes an array as input and returns a new array with the elements sorted.
  • Natural Sorting: Sorts the elements alphanumerically, treating sequences of digits within strings as numerical values for sorting purposes. For example, "file2" would come before "file10" because 2 is less than 10. This is different from a purely alphabetical sort, where "file10" would come before "file2."

Syntax

    {{ array_variable | sort_natural }} 
or

    {{ array_variable | sort_natural: 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 on the elements themselves.

Code Samples

Example 1: Natural Sorting (Mixed Alphanumeric)

    {% assign files = ["file1.txt", "file2.txt", "file10.txt", "file20.txt"] %}

    {{ files | sort_natural }} 

Output:

["file1.txt", "file2.txt", "file10.txt", "file20.txt"]
Example 2: Natural Sorting with Property
    {% assign items = [{ "name": "Item 2", "id": 10 }, 
                       { "name": "Item 10", "id": 2 }, 
                       { "name": "Item 1", "id": 20 }] %}

    {{ items | sort_natural: "name" }}
Output:
[{"name": "Item 1", "id": 20}, {"name": "Item 2", "id": 10}, {"name": "Item 10", "id": 2}]

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the sort_natural filter returns an empty array.
  • Non-Array Input: If the input is not an array, the sort_natural 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_natural filter is a specialized sorting tool designed to handle mixed alphanumeric data in a way that aligns with human intuition.
  • It is particularly useful when sorting filenames, version numbers, or other data that combines letters and numbers.
  • When the optional property_name is provided, it allows for natural sorting based on the values of that specific property within the objects of the array.