Diogo Antunes Diogo Antunes - 6 months ago 27
Swift Question

Join Multidimension Arrays

I have multiple arrays of different sizes, for instance:

let array1 = [[1, 2, 3], [1, 2, 3]]
let array2 = [[1, 2], [1, 2]]
let array3 = [[1, 2], [1, 2], [1, 2]]


And I wanna join them together so I get the final array:

let finalArray = [[1, 2, 3, 1, 2, 1, 2], [1, 2, 3, 1, 2, 1, 2], [1, 2]]


Any ideia on how can I achieve this goal in a efficient way?

Answer

Try like this:

var finalArray:[[Int]] = []
for index in 0..<max(array1.count,array2.count,array3.count) {
    finalArray.append([])
    if index < array1.count {
        finalArray[index].appendContentsOf(array1[index])
    }
    if index < array2.count {
        finalArray[index].appendContentsOf(array2[index])
    }
    if index < array3.count{
        finalArray[index].appendContentsOf(array3[index])
    }
}
finalArray // [[1, 2, 3, 1, 2, 1, 2], [1, 2, 3, 1, 2, 1, 2], [1, 2]]
Comments