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

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

asked Feb 25, 2016 at 20:46

2 Answers 2

4

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.

answered Feb 25, 2016 at 21:09
1

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"]
answered Feb 25, 2016 at 21:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.