1

I've these arrays.

let array1 = [10, 20, 30, 40, 50, 55]
let array2 = [11, 22, 33]

I want this output in only one array

[10, 11, 20, 22, 30, 33, 40, 50, 55]

In case the second array size is bigger than first one.

let array1 = [10, 20, 30]
let array2 = [11, 22, 33, 45, 56, 78]

Output

[10, 11, 20, 22, 30, 33, 45, 56, 78]

Is there a way without loop the arrays in a for?

Thanks

RMH
  • 169
  • 1
  • 14
  • 1
    Are the source arrays always sorted in increasing order? Can we assume that the result is sorted in increasing order? What would be the expected result for merging `[1, 2, 3]` with `[4, 5, 6]`? – Martin R Aug 05 '16 at 13:03
  • The source can be in sorted in order or not. The example can be confused. The result for your example may be. 1, 4, 2, 5, 3, 6 – RMH Aug 08 '16 at 06:26

1 Answers1

-1

You can use + operator for arrays, remove duplicates using Set and sort result:

let array1 = [10, 20, 30, 40, 50, 55]
let array2 = [11, 22, 33]

let mixedArray = Set(array1 + array2).sort(<)
print(mixedArray)
//[10, 11, 20, 22, 30, 33, 40, 50, 55]

This works for any input array sizes.

Yury
  • 6,044
  • 3
  • 19
  • 41