Thank you ElegyD. This is worked for me.
extension Sequence {
func groupSort(ascending: Bool = true, byDate dateKey: (Iterator.Element) -> Date) -> [[Iterator.Element]] {
var categories: [[Iterator.Element]] = []
for element in self {
let key = dateKey(element)
guard let dayIndex = categories.index(where: { $0.contains(where: { Calendar.current.isDate(dateKey($0), inSameDayAs: key) }) }) else {
guard let nextIndex = categories.index(where: { $0.contains(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) }) else {
categories.append([element])
continue
}
categories.insert([element], at: nextIndex)
continue
}
guard let nextIndex = categories[dayIndex].index(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) else {
categories[dayIndex].append(element)
continue
}
categories[dayIndex].insert(element, at: nextIndex)
}
return categories
}
}
Usage:
class Model {
let date: Date!
let anotherProperty: String!
init(date: Date, _ anotherProperty: String) {
self.date = date
self.anotherProperty = anotherProperty
}
}
let modelArray = [
Model(date: Date(), anotherProperty: "Original Date"),
Model(date: Date().addingTimeInterval(86400), anotherProperty: "+1 day"),
Model(date: Date().addingTimeInterval(172800), anotherProperty: "+2 days"),
Model(date: Date().addingTimeInterval(86401), anotherProperty: "+1 day & +1 second"),
Model(date: Date().addingTimeInterval(172801), anotherProperty: "+2 days & +1 second"),
Model(date: Date().addingTimeInterval(86400), anotherProperty: "+1 day"),
Model(date: Date().addingTimeInterval(172800), anotherProperty: "+2 days")
]
let groupSorted = modelArray.groupSort(byDate: { $0.date })
print(groupSorted) // [["Original Date"], ["+1 day", "+1 day", "+1 day & +1 second"], ["+2 days", "+2 days", "+2 days & +1 second"]]
let groupSortedDesc = modelArray.groupSort(ascending: false, byDate: { $0.date })
print(groupSortedDesc) // [["+2 days & +1 second", "+2 days", "+2 days"], ["+1 day & +1 second", "+1 day", "+1 day"], ["Original Date"]]