简体   繁体   中英

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]})

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 }

If you are trying to sort associated fields you should really consider using an object oriented approach using some kind of model, however, the following should achieve what you are trying to do:

var n = min(dates.count, people.count, peopleIds.count)
var tuples = (0 ..< n).map { (dates[$0], people[$0], peopleIds[$0]) }
    .sorted { $0.0 as Date > $1.0 as Date }
dates = tuples.map{ $0.0 }
people = tuples.map{ $0.1 }
peopleIds = tuples.map{ $0.2 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM