1) This is what I understand
arrayA defines some kind of order. In your example it is coincidentally the ascending order of integers but it can really be any kind of order like one of the following:
- Example 1: [5, 4, 1, 3, 2] Ascending by number "names" (five, four, one, three, two)
- Example 2: [5, 2, 4, 3, 1]: Ascending by italian names of numbers (cinque, due, quattro, tre, uno)
2) You don't like this kind of solution
arrayB = arrayA
You actually need a way to move the elements inside arrayB in order to make it sorted as arrayA (maybe because you need a solution for a more generic problem where the elements of the arrays are not simply integers).
3) Now, my solution
var arrayA = [1, 2, 3, 4, 5]
var arrayB = [4, 5, 1, 2, 3]
var indexes = [Int: Int]()
for (index, elm) in enumerate(arrayA) {
indexes[elm] = index
}
// now indexes[i] gives me the position of the integer i inside arrayA, e.g. indexes[3] -> 2
arrayB.sort { return indexes[$0] < indexes[$1] }
// now arrayB has been sorted as arrayA
Conclusion
This approach does work when:
- there are not duplicates in arrayA (or arrayB)
- arrayA.count == arrayB.count
- arrayA and arrayB contain the same elements
Please let me know if this is what you are looking for.