Search code examples
sortingdateswift3nsarray

Sort Array of Dates, but if past date drop to bottom of Array Swift


I need to sort a table by time and day for upcoming events. I need the nearest future date string at the top descending by the events following. BUT I want to drop past events to the bottom of the array/table, where I will hide the date and time, so the history is shown.

Its an Array of structs if that makes a difference

for example :

Event3 - 14:15

Event4 - 15:00

Event5 - 18:03

Event1 -

Event2 -

The following works to order my array, I just want to drop past dates to the bottom

newArray = oldArray.sorted(by: {Date(timeIntervalSinceNow: $0.eventTime < Date(timeIntervalSinceNow: $1.eventTime})

Solution

  • Solution A: sort, split and combine

    let now = Date()
    let sortedArray = myArray.sorted(by: { $0.startTime < $1.startTime })
    var finalArray = sortedArray
    if let index = sortedArray.index(where: { $0.startTime > now }) {
        if index > 0 {
            finalArray = Array(sortedArray[index ..< sortedArray.endIndex] + sortedArray[sortedArray.startIndex ... index - 1])
        }
    }
    

    Solution B (faster): sort by a predicate

    let now = Date()
    let newArray = myArray.sorted(by: {
        if $0.startTime > now {
            if $1.startTime > now {
                return $0.startTime < $1.startTime
            } else {
                return true
            }
        } else {
            if $1.startTime > now {
                return false
            } else {
                return $0.startTime < $1.startTime
            }
        }
    })