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?
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)
CodePudding user response:
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"]]