Search code examples
arraysswiftsortingfilterarray-filter

Sort Arrays based on Month and Year String


What is the best way to sort an Array which Contains a month and Year in the following format:

let dateX2 = Date(); let formatter2 = DateFormatter()
formatter2.dateFormat = "MMMM,,yyyy"
let dateZ = formatter2.string(from: dateX2)

Array containing the above formatted dates not in correct order:

let array = ["July,,2019", "January,,2020", "February,,2019", "March,,2020"]

Expected result following sorting:

let result = ["February,,2019", "July,,2019", "January,,2020", "March,,2020"]

Solution

  • Use an array of Date objects instead as your data source and then sort and format the dates to your expected output

    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM,,yyyy"
    
    let sortedArry = array.sorted(by: {$0 < $1}).map {formatter.string(from: $0)}
    

    Example input

    let oneMonth = 3600 * 24 * 30.5 //I know :) but its just to generate som test data
    let array = [
        Date(timeIntervalSinceNow: -9 * oneMonth),
        Date(timeIntervalSinceNow: -3 * oneMonth),
        Date(timeIntervalSinceNow: -4 * oneMonth),
        Date(timeIntervalSinceNow: -10 * oneMonth),
    ]
    

    gives

    ["October,,2019", "November,,2019", "April,,2020", "May,,2020"]