Map each array element to a (element, index)
tuple, where
the index is the index of the array element in the order array.
In your example that would be
[("Lieutenant", 2), ("Captain", 1)]
Sort the array of tuples by the second tuple element (the index).
In your case
[("Captain", 1), ("Lieutenant", 2)]
Extract the array elements from the sorted tuples array.
In your case
["Captain", "Lieutenant"]
Code (for any array of equatable elements, not restricted to arrays of strings):
extension Array where Element: Equatable {
func getSorted(by orderArray: [Element]) -> [Element] {
return self.map { ($0, orderArray.index(of: $0) ?? Int.max) }
.sorted(by: { $0.1 < $1.1 })
.map { $0.0 }
}
}
let orderSettingArray = ["Admiral", "Captain", "Lieutenant"]
let myArray = ["Lieutenant", "Captain"]
let myArraySorted = myArray.getSorted(by: orderSettingArray)
print(myArraySorted) // ["Captain", "Lieutenant"]
Elements in myArray
which are not present in orderSettingArray
are assigned the index Int.max
and therefore sorted to the end
of the result.