Handlebar Helper Function: Sort
Sorts a list of objects by a specified field, order, and type. Supports sorting as string, number, date, or boolean.
| Parameter | Type | Description |
|---|---|---|
list | array | Required. The list of objects to sort. |
fieldName | string | Required. The field to sort by. Must exist in all objects. |
sortOrder | string | Required. The sort order. Valid values are "asc" (ascending order) and "desc" (descending order). |
sortAs | string | Required. The type to sort as. Valid values:
|
The function returns a new list sorted by the specified field, order, and type. Objects with missing fields or invalid values for the specified type are excluded from the result. If a parameter is missing or invalid, the function throws an exception.
This example shows how to use the sort function to sort a list of objects by the age field in ascending order.
The function returns [{"age": 21}, {"age": 24}, {"age": 27}].
When the field is a string, the function sorts the strings in alphabetical order, as shown in this example.
The function returns [{"name": "Alice"}, {"name": "Bob"}, {"name": "John"}].
When the field is a boolean, the function sorts the booleans with false before true, as shown in this example.
The function returns [{"isActive": false}, {"isActive: true}].
You can combine the sort function with the filter function to filter a list by one field, and then sort the resulting list by another field.
This example shows how to use the sort function with the filter function to sort a list of objects by the createdAt field in descending order, only including objects where the value of the total field is greater than 100.
The function returns this list: