Swift2 - 根据另一个INT数组的排序顺序对多个数组进行排序

时间:2016-02-25 20:46:18

标签: arrays sorting swift2 sorted

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的重复 我已经尝试了答案而且没有用

2 个答案:

答案 0 :(得分:3)

创建一个新的索引数组,按照您希望“降序”的方式排序,然后映射其他数组。

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

我刚刚测试了这个解决方案,效果很好。

答案 1 :(得分:1)

这是使用您自己的数据的解决方案。

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"]