JSONATA - soting on multiple fields of objects in an array

Hi, me and JSONATA again....

I can sort on a field within an array. Now I want to sort on multiple fields. This is failing.

So, firstly, the array...

[
{"taskName":"Leg2","prio":2,"startAfter":"11h00"},
{"taskName":"Leg1","prio":2,"startAfter":"10h00"},
{"taskName":"Leg0","prio":1,"startAfter":"09h30"}
]

Sorting using a Sort node, with jsonata expression of the following single field works:

(
   $sort(
       payload,
       function($l , $r){$l.prio > $r.prio }
   ) 
)

But all expressions I tried to also sort using say field startAfter does not work, any ideas please?

Two methods, hope example helps. Orderby is cleaner

[{"id":"187967a.a95e618","type":"inject","z":"4484ee28.caa3c","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[ {\"taskName\":\"Leg2\",\"prio\":2,\"startAfter\":\"11h00\"}, {\"taskName\":\"Leg1\",\"prio\":2,\"startAfter\":\"10h00\"}, {\"taskName\":\"Leg0\",\"prio\":1,\"startAfter\":\"09h30\"} ]","payloadType":"json","x":130,"y":500,"wires":[["67f3f52c.e2114c"]]},{"id":"269a25ff.79887a","type":"debug","z":"4484ee28.caa3c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":590,"y":360,"wires":[]},{"id":"67f3f52c.e2114c","type":"change","z":"4484ee28.caa3c","name":"","rules":[{"t":"set","p":"sort","pt":"msg","to":"(\t   $sort(\t       (\t   $sort(\t       payload,\t       function($l , $r){$l.startAfter > $r.startAfter }\t   ) \t),\t       function($l , $r){$l.prio > $r.prio }\t   ) \t)","tot":"jsonata"},{"t":"set","p":"orderby","pt":"msg","to":"payload^(prio, startAfter)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":350,"y":500,"wires":[["269a25ff.79887a"]]}]
2 Likes

Wow.... 2nd one so elegant. Thank you !

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.