Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I order hours(am/pm) array

Firstly I have to say this.

ÖÖ: AM
ÖS: PM

I have hours array like that:

[["12:15 ÖS", "02:00 ÖS"],["09:00 ÖÖ", "10:00 ÖÖ"],["10:30 ÖÖ", "12:00 ÖS"]]

How can I sort by first hour of the day?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 let testArray = [["12:15 ÖS", "02:00 ÖS"],["09:00 ÖÖ", "10:00 ÖÖ"],["10:30 ÖÖ", "12:00 ÖS"]]
    var convertedArray: [[Date]] = []

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    dateFormatter.timeStyle = .short
    dateFormatter.locale = Locale(identifier: "en-US")

    for dat in testArray {
        let firstDate = dateFormatter.date(from: dat[0])
        let secondDate = dateFormatter.date(from: dat[1])
        if let firstDate = firstDate, let secondDate = secondDate {
            convertedArray.append([firstDate, secondDate])
        }
    }

    var ready = convertedArray.sorted(by: { $0.first?.compare($1.first ?? Date()) == .orderedAscending })

print(ready)

>Solution :

Just take the first element and sorted after it

let testArray = [["12:15 ÖS", "02:00 ÖS"],["09:00 ÖÖ", "10:00 ÖÖ"],["10:30 ÖÖ", "12:00 ÖS"]]

let sortArray = testArray.sorted {
    $0[0] < $1[0]
}

print(sortArray) // [["09:00 ÖÖ", "10:00 ÖÖ"], ["10:30 ÖÖ", "12:00 ÖS"], ["12:15 ÖS", "02:00 ÖS"]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading