Search code examples
iosswiftswift3

Swift Map ARRAYS by Date Array


Im trying to accomplish this: [Swift2 - Sort multiple arrays based on the sorted order of another INT array But I have to sort by NSDate array.

// dates are actual NSDates, I pasted strings into my sample
var dates:[NSDate] = [2019-12-20 13:00 +0000, 2019-12-20 13:00 +0000, 2019-12-12 13:00 +0000]
var people:[String] = ["Harry", "Jerry", "Hannah"]
var peopleIds:[Int] = [1, 2, 3, 4]


// the following line doesn't work.
// i tried a few variations with enumerated instead of enumerate and sorted instead of sort
// but with now luck
let sortedOrder = dates.enumerate().sort({$0.1>$1.1}).map({$0.0})

dates = sortedOrder.map({points[$0]})
people = sortedOrder.map({people[$0]})
peopleIds = sortedOrder.map({peopleIds[$0]})

Solution

  • Change your dates declaration from NSDate to Date. Date conforms to Comparable protocol since Swift 3.0. Doing so you can simply sort your dates dates.sorted(by: >). To sort your arrays together you can zip your arrays, sort it by dates and map the sorted elements:

    let sortedZip = zip(dates, zip(people, peopleIds)).sorted { $0.0 > $1.0}
    let sortedPeople = sortedZip.map{ $0.1.0 }
    let sortedIDs = sortedZip.map{ $0.1.1 }