2

I wanted to do reverse ordering using Date field from highest to lowest (DSC). This question is similar to the below link Reverse ordering in Mule4. Thought small tweaks would make the fix. Tried various ways.Not working. When I try to format date it says the key cant be formatted to date or it complains about -. Any thoughts? Thanks

%dw 2.0
output application/json
var test = { "2022-10-19":[{"kio":"spotage"}] ,
            "2022-10-17": [{"kio":"spotage"}] ,
            "2022-10-18": [{"kio":"spotage"}] 
            }
---
test orderBy -($$ as String as Date {format: "yyyy-MM-dd"}

)

Expected Response:

{
    "2022-10-19": [
        {
            "kio": "spotage"
        }
    ],
    "2022-10-18": [
        {
            "kio": "spotage"
        }
    ],
    "2022-10-17": [
        {
            "kio": "spotage"
        }
    ]
}
aled
  • 21,330
  • 3
  • 27
  • 34
star
  • 1,493
  • 1
  • 28
  • 61

1 Answers1

3

The orderBy() function seems to be expecting a number to be able to do reverse sorting. A Date can not be converted directly to a number in DataWeave. However the date format 'yyyyMMdd' can be converted to a number that can directly sorted.

Example:

%dw 2.0
output application/json
var test =  { 
                "2022-10-18":[{"kio":"spotage"}],
                "2022-10-17": [{"kio":"spotage"}],
                "2022-10-19": [{"kio":"spotage"}] 
            }
---
test orderBy -($$ as String as Date {format: "yyyy-MM-dd"} as String {format: "yyyyMMdd"} as Number)

I modified the input to show that the script actually orders the output.

aled
  • 21,330
  • 3
  • 27
  • 34
  • I tried all the possible way for making as Date format and converted as Number- Didnt work. Haven't know {format: "yyyyMMdd"} do. Learning for me. Thanks for explaining in details.@Aled. As always appreciate it. – star Nov 06 '22 at 20:13
  • 1
    You can use Java date time pattern characters in DataWeave. – aled Nov 06 '22 at 20:15