2016-02-25 75 views
0
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"] 

我怎麼能由點這個數組進行排序是?:Swift2 - 基於另一個INT數組的排序順序排序上的多個陣列

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 我已經試過答案和它不工作

回答

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

這裏是您自己的數據解決方案。

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"] 
相關問題