Reputation: 992
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
Upvotes: 0
Views: 470
Reputation: 17534
here is the solution with your own data.
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"]
Upvotes: 1
Reputation: 2078
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.
Upvotes: 4