Swift2-根据另一个INT数组的排序顺序对多个数组进行排序
问题描述:
let points:[Int] = [200, 1000, 100, 500]
let people:[String] = ["Harry", "Jerry", "Hannah", "John"]
let peopleIds:[Int] = [1, 2, 3, 4]
let sex:[String] = ["Male", "Male", "Female", "Male"]
如何按要排序的点对这些数组进行排序?:
How can I sort this arrays by points to be?:
let points:[Int] = [1000, 500, 200, 100]
let people:[String] = ["Jerry", "John", "Harry", "Hannah"]
let peopleIds:[Int] = [2, 4, 1, 3]
let sex:[String] = ["Male", "Male", "Male", "Female"]
It's not duplicate of How to sort 1 array in Swift / Xcode and reorder multiple other arrays by the same keys changes I've tried with the answers and it's not working
答
创建一个新的索引数组,该数组按照您希望的降序"排序,然后映射其他数组.
Create a new array of indexes sorted the way you want "descending" and then map the other arrays.
var points:[Int] = [200, 1000, 100, 500]
var people:[String] = ["Harry", "Jerry", "Hannah", "John"]
var peopleIds:[Int] = [1, 2, 3, 4]
var sex:[String] = ["Male", "Male", "Female", "Male"]
//descending order array of indexes
let sortedOrder = points.enumerate().sort({$0.1>$1.1}).map({$0.0})
//Map the arrays based on the new sortedOrder
points = sortedOrder.map({points[$0]})
people = sortedOrder.map({people[$0]})
peopleIds = sortedOrder.map({peopleIds[$0]})
sex = sortedOrder.map({sex[$0]})
我刚刚测试了此解决方案,并且效果很好.
I just tested this solution out and it works well.