In Swift, say I have two arrays:
var array1: [Int] = [100, 40, 10, 50, 30, 20, 90, 70]
var array2: [Int] = [50, 20, 100, 10, 30]
I want to sort my aary1 as per array2
So final output of my array1 will be: // array1 = [50, 20, 100, 10, 30, 40, 90, 70]
-
1Possible duplicate of Sort array by order of values in other array or Reorder array compared to another array in SwiftMartin R– Martin R2017年08月10日 14:58:28 +00:00Commented Aug 10, 2017 at 14:58
2 Answers 2
Even though your question is quite vaguely worded, judging from your example, what you actually want is the union of the two arrays, with the elements of the smaller array coming in first and after them the unique elements of the bigger array in an unchanged order at the end of this array.
The following code achieves the result of the example:
let combined = array2 + array1.filter{array2.index(of: 0ドル) == nil}
-
It does work, since it keeps the unique elements of both arrays. The question didn't specify what should the ordering be if none of the arrays is a subset of the other, so in this case they are just concatenated.David Pasztor– David Pasztor2017年08月10日 14:57:52 +00:00Commented Aug 10, 2017 at 14:57
-
@LucaAngeletti it was a general comment toward the person, who actually did, hence I didn't tag you.David Pasztor– David Pasztor2017年08月11日 10:55:41 +00:00Commented Aug 11, 2017 at 10:55
You have not defined how you want the elements in array1
but not in array2
to be sorted. This solution assumes you want to sort those not-found elements by their numeric value:
var array1 = [100, 40, 10, 50, 30, 20, 90, 70]
var array2 = [50, 20, 100, 10, 30]
array1.sort {
let index0 = array2.index(of: 0ドル)
let index1 = array2.index(of: 1ドル)
switch (index0, index1) {
case (nil, nil):
return 0ドル < 1ドル
case (nil, _):
return false
case (_, nil):
return true
default:
return index0! < index1!
}
}
print(array1) // [50, 20, 100, 10, 30, 40, 70, 90]
// ^ order not defined in array2