Sort
2 minute read
The Sort converter sorts a slice in ascending or descending order.
Syntax: Sort(target, Optional[order])
- target: a slice containing elements to be sorted
- order: an optional string specifying sort order:
"asc"(default) or"desc"
The Sort converter preserves the data type of the original elements while sorting. The behavior varies based on the types of elements:
| Element Types | Sorting Behavior | Return Value |
|---|---|---|
| Integers | Sorts as integers | Sorted array of integers |
| Doubles | Sorts as doubles | Sorted array of doubles |
| Integers and doubles | Converts all to doubles, then sorts | Sorted array of integers and doubles |
| Strings | Sorts as strings | Sorted array of strings |
| Booleans | Converts all to strings, then sorts | Sorted array of booleans |
| Mix of integers, doubles, booleans, and strings | Converts all to strings, then sorts | Sorted array of mixed types |
| Any other types | N/A | Returns an error |
Example 1: Sorting integers in ascending order (default)
Input
{
"_type": "log",
"body": {
"unsorted": [5, 2, 8, 1],
"run": 23
},
"resource": {...},
"timestamp": 1727750400000
}
Statement
set(body["sorted"], Sort(body["unsorted"]))
Output
{
"_type": "log",
"body": {
"unsorted": [5, 2, 8, 1],
"sorted": [1, 2, 5, 8],
"run": 23
},
"resource": {...},
"timestamp": 1727750400000
}
The array [5, 2, 8, 1] was sorted in ascending order to produce [1, 2, 5, 8].
Example 2: Sorting in descending order
Input
{
"_type": "log",
"body": {
"tags": ["warning", "error", "debug", "info"],
"run": 24
},
"resource": {...},
"timestamp": 1727750400000
}
Statement
set(body["sorted_tags"], Sort(body["tags"], "desc"))
Output
{
"_type": "log",
"body": {
"tags": ["warning", "error", "debug", "info"],
"sorted_tags": ["warning", "info", "error", "debug"],
"run": 24
},
"resource": {...},
"timestamp": 1727750400000
}
The string array was sorted in descending (reverse alphabetical) order.