Swift 2 – Merge two arrays

Swift 2 – Merge two arrays

I am trying to merge two array:
array 1
[["aaa","111"],["bbb","222"],["ccc","333"]]
array 2
[["ddd","444"],["eee","555"],["fff","666"]]
What I want to achieve is to have a single array with the values respecting the array positions such as:
merged array
[["aaa","111"],["ddd","444"],["bbb","222"],["eee","555"],["ccc","333"],["fff","666"]]
How could I do this using Swift 2

Solutions/Answers:

Answer 1:

let arr1 = [["aaa","111"],["bbb","222"],["ccc","333"]]
let arr2 = [["ddd","444"],["eee","555"],["fff","666"]]
let arr3 = arr1 + arr2
print(arr3) // [["aaa", "111"], ["bbb", "222"], ["ccc", "333"], ["ddd", "444"], ["eee", "555"], ["fff", "666"]]

in you case, with specific requirements

let arr4 = zip(arr1, arr2).reduce([]) { (var arr, p:(Array<String>, Array<String>)) -> [[String]] in
    arr.append(p.0)
    arr.append(p.1)
    return arr
}
print(arr4) // [["aaa", "111"], ["ddd", "444"], ["bbb", "222"], ["eee", "555"], ["ccc", "333"], ["fff", "666"]]

UPDATE
in accordance with your needs mentioned in notes you can add the rest of values this way (please change let arr4 to var arr4 first!!!)

var i = arr4.count / 2
while i < arr1.count {
    arr4.append(arr1[i++])
}

while i < arr2.count {
    arr4.append(arr2[i++])
}
print(arr4)

this gives you

[["aaa", "111"], ["ddd", "444"], ["bbb", "222"], ["eee", "555"], ["ccc", "333"], ["fff", "666"], ["zzz", "755"]]

it should work, even though one of the arrays is empty

Answer 2:

use zip function

Array(zip(arr1, arr2))

@edit

as @user3441734 mentioned zip returns tupes. To fix that you can use flatMap

var a = [["aaa","111"],["bbb","222"],["ccc","333"]] 
var b = [["ddd","444"],["eee","555"],["fff","666"]]
var cos = Array(zip(a, b))
var eee = cos.flatMap { [$0.0, $0.1] }

result:

[["aaa", "111"], ["ddd", "444"], ["bbb", "222"], ["eee", "555"],["ccc", "333"], ["fff", "666"]]

short answer:

var result = zip(arr1, arr2).flatMap { [$0.0, $0.1] }

References

Loading...