How do I sort and array of json that needs sorting by date using Dataweave 2
{
"things": [
{
"datetime": "2020-11-07T16:11:52.866Z",
"name": "foo"
},
{
"datetime": "2020-11-07T16:11:39.971Z",
"name": "bar"
},
{
"datetime": "2020-11-07T16:11:39.978Z",
"name": "baz"
}
]
}
You can use the orderBy
function
%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy $.datetime)
By default the output is in ascending order.
If you need descending you can do this:
%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy $.datetime)[-1 to 0]
Also you can use datetime formatting if you get inputs with different timezones. With your current input values you can use LocalDateTime
%dw 2.0
output application/json
---
orderedDates: (payload.things orderBy ($.datetime as LocalDateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"}))