I would like to know how to sort a collection in mule using Dataweave orderBy with multiple number of fields and also with ascending or descending order.
3 Answers
Here is the sample code(with example) that I created to demonstrate multiple orderby and sorting. Note:- By default, the order by is ascending order and to achieve the descending order, just reverse the result at the end by [-1..0].
%dw 1.0
%var inputPayload=[
{"name":"john",
"age": "12"
},
{"name":"john3",
"age": "15"
},
{"name":"john3",
"age": "14"
},
{"name":"john1",
"age": "13"
},
{"name":"john2",
"age": "14"
},
{"name":"john5",
"age": "17"
}
]
%output application/json
---
((inputPayload orderBy $.name) orderBy $.age)[-1..0]
Output Payload - [ { "name": "john5", "age": "17" }, { "name": "john3", "age": "15" }, { "name": "john3", "age": "14" }, { "name": "john2", "age": "14" }, { "name": "john1", "age": "13" }, { "name": "john", "age": "12" } ]
I think the accepted answer just re-orders the entire array twice and only works for that particular example. If you use an example where the age
a number instead of a string like so
{
"input": [
{
"name": "john",
"age": 12
},
{
"name": "john5",
"age": 7
},
{
"name": "john3",
"age": 15
},
{
"name": "john3",
"age": 14
},
{
"name": "john1",
"age": 13
},
{
"name": "john2",
"age": 14
}
]
}
then the output ends up in the wrong order for a multi-layer orderBy (it's the order you would expect if we just did orderBy age
)
[
{
"name": "john3",
"age": 15
},
{
"name": "john3",
"age": 14
},
{
"name": "john2",
"age": 14
},
{
"name": "john1",
"age": 13
},
{
"name": "john",
"age": 12
},
{
"name": "john5",
"age": 7
}
]
whereas something like
flatten(((inputPayload orderBy $.name) groupBy $.name) pluck ($ orderBy $.age))[-1..0]
gives
[
{
"name": "john5",
"age": 7
},
{
"name": "john3",
"age": 15
},
{
"name": "john3",
"age": 14
},
{
"name": "john2",
"age": 14
},
{
"name": "john1",
"age": 13
},
{
"name": "john",
"age": 12
}
]
so the overall orderBy is name
and then within the same name the orderBy is age