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
541k98 gold badges1.3k silver badges1.4k bronze badges
asked Aug 10, 2017 at 14:42
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}
answered Aug 10, 2017 at 14:54
2
  • 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. Commented Aug 10, 2017 at 14:57
  • @LucaAngeletti it was a general comment toward the person, who actually did, hence I didn't tag you. Commented Aug 11, 2017 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
answered Aug 10, 2017 at 16:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.