2

I am wondering is there any build-in function I can sort a array according to another array. For example: sort testStringArray according to testIntArray

var testStringArray = ["a", "b", "c", "d", "e"] var testIntArray = [21, 3, 43, 5, 1]

After the function, testStringArray will be

testIntArray.sort // [1, 3, 5, 21, 43]
testStringArray // ["e", "b", "d", "a", "c"]

1 Answer 1

3
var array1 = ["a", "b", "c", "d", "e"]
var array2 = [21, 3, 43, 5, 1]

let sorted = zip(array1, array2).sort { $0.1 < $1.1 }

array1 = sorted.map { $0.0 }
array2 = sorted.map { $0.1 }

print(array1) // ["e", "b", "d", "a", "c"]
print(array2) // [1, 3, 5, 21, 43]

Something like this? I feel like it can be done better...

EDIT:

This doesn't feel like it's much better...

zip(array1, array2).sort { $0.1 < $1.1 }.forEach {
    array1.removeAtIndex(array1.indexOf($0.0)!)
    array1.insert($0.0, atIndex: array1.count)

    array2.removeAtIndex(array2.indexOf($0.1)!)
    array2.insert($0.1, atIndex: array2.count)
}

print(array1) // ["e", "b", "d", "a", "c"]
print(array2) // [1, 3, 5, 21, 43]
Sign up to request clarification or add additional context in comments.

4 Comments

Yup. I am trying to find the simplest way to sort it because my way to do that is to define a new function to sort the second array according to the first array.
Well, my answer is pretty simple. It's just I feel like I can cut one more step :)
Ya. Yours is much simpler than mine. Thank you for your help
I think the first way you make is better because I don't want to modify the arrays.

Your Answer

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.