Swift2 - 根据另一个 INT 数组的排序顺序对多个数组进行排序
Posted
技术标签:
【中文标题】Swift2 - 根据另一个 INT 数组的排序顺序对多个数组进行排序【英文标题】:Swift2 - Sort multiple arrays based on the sorted order of another INT array 【发布时间】:2016-02-25 20:46:17 【问题描述】: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"]
如何按点对这些数组进行排序?:
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"]
它不是 How to sort 1 array in Swift / Xcode and reorder multiple other arrays by the same keys changes 的重复项 我已经尝试了答案,但它不起作用
【问题讨论】:
【参考方案1】:创建一个新的索引数组,按照您想要的“降序”排序,然后映射其他数组。
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])
我刚刚测试了这个解决方案,它运行良好。
【讨论】:
【参考方案2】:这是使用您自己的数据的解决方案。
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"]
let sortedPointsEnumerateIndexes = points.enumerate().sort $0.element > $1.element.map $0.index
var sortedPoints:[Int] = []
var sortedPeople:[String] = []
var sortedPeopleIds:[Int] = []
var sortedSex:[String] = []
for i in sortedPointsEnumerateIndexes
sortedPoints.append(points[i])
sortedPeople.append(people[i])
sortedPeopleIds.append(peopleIds[i])
sortedSex.append(sex[i])
print(sortedPoints) // [1000, 500, 200, 100]
print(sortedPeople) // ["Jerry", "John", "Harry", "Hannah"]
print(sortedPeopleIds) // [2, 4, 1, 3]
print(sortedSex) // ["Male", "Male", "Male", "Female"]
// with map
let sorted2Point = sortedPointsEnumerateIndexes.map points[$0]
let sorted2People = sortedPointsEnumerateIndexes.map people[$0]
// ....
print(sorted2Point) // [1000, 500, 200, 100]
print(sorted2People) // ["Jerry", "John", "Harry", "Hannah"]
【讨论】:
以上是关于Swift2 - 根据另一个 INT 数组的排序顺序对多个数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章
如何根据数组索引从数组复制到 Vector256,反之亦然?