sort Statement
Sort an array by using an expression to compare array elements with each other.
Syntax |
| |
---|---|---|
Semantics |
Be aware that sort algorithms are not linear (typically n log n to n2 iterations for n elements). Therefore, you should keep the expression as compact as possible. The sort algorithm will call the expression each time two elements need to be compared. The expression must either return a boolean or an integer value. This means the following:
When using a boolean expression, make sure that equality always returns true (e.g. by using <= instead of <). Otherwise, the implemented sort algorithm may take longer than necessary or not terminate at all. | |
Substitutables |
| Can be any variable or object attribute having the type Array. |
| This expression must use the currently evaluated array element and its next neighbor and indicates if the current order is OK or not. | |
| ||
Examples | Sort an array of strings in descending order Input: an array of names
JSON
CODE
Result:
JSON
| |
Sort an array of integers in ascending order Input: an array of integers
JSON
CODE
Result:
JSON
|
Sort an array with complex elements
Sort over two sort keys (string and integer)
The compare expression can be complex and implement a sort by e.g. two sort keys.
Input: an array of a complex article (sort by category and serviceInterval)
{ "articles": [
{"name": "AF-1200", "category": "Adapter", "serviceInterval": 52},
{"name": "CD-2024", "category": "Connector", "serviceInterval": 208},
{"name": "RC-0002", "category": "Adapter", "serviceInterval": 104},
{"name": "CD-2002", "category": "Connector", "serviceInterval": 26}
]}
set result = sort articles
using (element.category = nextElement.category
and element.serviceInterval <= nextElement.serviceInterval)
or element.category < nextElement.category;
Result:
{ "articles": [
{"name": "AF-1200", "category": "Adapter", "serviceInterval": 52},
{"name": "RC-0002", "category": "Adapter", "serviceInterval": 104},
{"name": "CD-2002", "category": "Connector", "serviceInterval": 26},
{"name": "CD-2024", "category": "Connector", "serviceInterval": 208}
]}
Sort using a complex compare expression
Sometimes compare expressions can be more complex and e.g. include conditions or calculations. You can implement this to the sort statement by providing a dedicated, own compare operation.
set result = sort articles using compareArticles(element, nextElement);
or
set result = sort articles using element.compareArticles(nextElement);
compareArticles, in this case, is a custom operation that needs to get two array elements as input, compares them, and returns the result of the comparison either as a boolean or an integer value (see Semantics above).