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]

1

2 Answers 2

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}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@LucaAngeletti it was a general comment toward the person, who actually did, hence I didn't tag you.
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

Comments

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.