Search code examples
muledataweavemulesoft

How to make orderBy() order numbers after alphabetic characters?


While trying to sort data in ascending order in DataWeave, I've noticed that if the input for orderBy() contains strings that start with numbers and alphabetic characters like ["6", "7", "a", "8"], then the result is ["6","7","8","a"].

Is there a way that we can have strings which are starting with alphabetic characters before numbers?


Solution

  • By default in Unicode digits are before alphabet characters. You can use the criteria parameter of orderBy() to change the way numbers are going to be compared with characters. For example adding character { as a prefix which is a character that is just ufter z (lowercase z), then numbers will be after any alphabet characters.

    Example:

    %dw 2.0
    output application/json
    import isNumeric from dw::core::Strings
    ---
    payload orderBy (if (isNumeric($)) "{" ++ $ else $ )
    

    Output:

    [
      "a",
      "6",
      "7",
      "8"
    ]