1

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]

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Nick
  • 1,127
  • 2
  • 15
  • 40
  • 1
    Possible duplicate of [Sort array by order of values in other array](https://stackoverflow.com/questions/44017101/sort-array-by-order-of-values-in-other-array) or [Reorder array compared to another array in Swift](https://stackoverflow.com/questions/39273370/reorder-array-compared-to-another-array-in-swift) – Martin R Aug 10 '17 at 14:58

2 Answers2

1

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}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • 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. – Dávid Pásztor Aug 10 '17 at 14:57
  • @LucaAngeletti it was a general comment toward the person, who actually did, hence I didn't tag you. – Dávid Pásztor Aug 11 '17 at 10:55
1

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
Code Different
  • 90,614
  • 16
  • 144
  • 163