I have a requirement to sort data based on a defined list, not alphabetically and not numerically. Sorting order is in a variable "sortOrder"
%dw 2.0
output application/json
var sortOrder = [ "Brad", "Alex", "Dan", "Chad"]
var myPayload = [
{
"Name": "Dan",
"Id": "3"
},
{
"Name": "Brad",
"Id": "4"
},
{
"Name": "Alex",
"Id": "2"
}
{
"Name": "Chad",
"Id": "1"
}
{
"Name": "Dan",
"Id": "5"
}
]
---
myPayload
The output needs to be like this.
[
{
"Name": "Brad",
"Id": "4"
},
{
"Name": "Alex",
"Id": "2"
},
{
"Name": "Dan",
"Id": "3"
},
{
"Name": "Dan",
"Id": "5"
},
{
"Name": "Chad",
"Id": "1"
}
]
There are 2 entries for Dan, in this case the sorting should be based on "Id"
You can order by the index of the sortOrder elements using Name to find it.
%dw 2.0
import * from dw::core::Arrays
output application/json
var sortOrder = [ "Brad", "Alex", "Dan", "Chad"]
var myPayload = [
{
"Name": "Dan",
"Id": "3"
},
{
"Name": "Brad",
"Id": "4"
},
{
"Name": "Alex",
"Id": "2"
},
{
"Name": "Chad",
"Id": "1"
},
{
"Name": "Dan",
"Id": "5"
}
]
---
myPayload orderBy( indexOf(sortOrder, $.Name) )