Search code examples
xquerymarklogic

MarkLogic Xquery: How to sort string values in a for loop


I've got a sequence that needs to sort a list based off earliest year vs. latest year. Due to some unique values in the year element, it is making the sort a little more complicated. Is there any way to achieve the following?

let $dates := ('1982', '2019', '2095', 'pre-1982', 'post-2095')
return    
for $date in $dates
order by $date
return $date

the dates element text is usually the year in the data, but outlier cases have a pre- or post- attached. Any way to achieve this minimally?


Solution

  • I am not sure if this is minimal, but it works:

    let $dates := ('1982', '2019', '2095', 'pre-1982', 'post-2095')
    return    
    for $date in $dates
    let $year := 
            if (fn:contains($date, "-")) 
            then fn:substring-after($date, "-") 
            else $date
    
    let $prepost := 
            if (fn:starts-with($date, "pre")) 
            then -1 
            else if (fn:starts-with($date, "post")) 
            then 1
            else 0
    order by $year, $prepost
    return $date