Skip to main content

$sort

$sort(array, function?) -> array
Compact type signature<af?:a>

Source: JSONata

Documentation

Returns an array containing all the values in the array parameter, but sorted into order. If no function parameter is supplied, then the array parameter must contain only numbers or only strings, and they will be sorted in order of increasing number, or increasing unicode codepoint respectively.

If a comparator function is supplied, then is must be a function that takes two parameters:

function(left, right)

This function gets invoked by the sorting algorithm to compare two values left and right. If the value of left should be placed after the value of right in the desired sort order, then the function must return Boolean true to indicate a swap. Otherwise it must return false.

Examples

Sort claim lines by allowed amount (descending)

Input

This example uses the claims-lines example input. The expression sorts the claim lines by allowedAmount.

Example input

JSON
[
{
"claimId": "clm-2001",
"lineNumber": 1,
"serviceCode": "PROC-010",
"serviceDisplay": "office visit",
"units": 1,
"unitPrice": 125,
"allowedAmount": 110,
"modifiers": [
"MOD-A"
]
},
{
"claimId": "clm-2001",
"lineNumber": 2,
"serviceCode": "PROC-020",
"serviceDisplay": "imaging study",
"units": "1",
"unitPrice": 350,
"allowedAmount": 300,
"modifiers": [
"MOD-B",
"MOD-C"
]
},
{
"claimId": "clm-2001",
"lineNumber": 3,
"serviceCode": "PROC-030",
"serviceDisplay": "lab panel",
"units": 2,
"unitPrice": 40,
"allowedAmount": 70,
"modifiers": []
},
{
"claimId": "clm-2002",
"lineNumber": 1,
"serviceCode": "PROC-010",
"serviceDisplay": "office visit",
"units": 1,
"unitPrice": 125,
"allowedAmount": 115,
"modifiers": [
"MOD-A"
]
},
{
"claimId": "clm-2002",
"lineNumber": 2,
"serviceCode": "PROC-040",
"serviceDisplay": "counseling",
"units": 3,
"unitPrice": 60,
"allowedAmount": 150,
"modifiers": [
"MOD-D"
]
}
]

Expression

$sort($, function($left, $right) { $left.allowedAmount < $right.allowedAmount }).allowedAmount

Result

[300, 150, 115, 110, 70]