How to Flatten an Array in Swift

flatten an array in swift

To flatten a 2D array in Swift:

  1. Call Array.joined() on an array.
  2. Convert the result to an array using Array().

For example:

let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flatData = Array(arr.joined())

print(flatData)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Notice that this only flattens out one dimension.

For example, if you have an array of arrays of arrays, the result is an array of arrays:

let arr = [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]
let flatData = Array(arr.joined())

print(flatData)

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

To flatten a multidimensional array like this, you need repeat the above process as many times as there are dimensions to reduce:

let arr = [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]
let flatData = Array(Array(arr.joined()).joined())

print(flatData)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

This is pretty easy.

Next, let’s increase the complexity of the problem by introducing arrays with elements of different dimensions.

How to Flatten an Array of Elements with Different Dimensions

Let’s increase the complexity of the multi-dimensional array. This time, let’s make the array contain arrays of different dimensions.

Doing this makes the flattening process a bit trickier.

let arr = [[1, [2, 3]], [4, 5, [6]], [7, [8, [9]]]]
let flatData = Array(arr.joined())

print(flatData)

Output:

[1, [2, 3], 4, 5, [6], 7, [8, [9]]]

The flattened array only got rid of one dimension and the deeply nested arrays are still multi-dimensional.

If you call .joined() on the already flattened array, you get an error:

let arr = [[1, [2, 3]], [4, 5, [6]], [7, [8, [9]]]]
let flatData = Array(arr.joined())

print(flatData.joined())

Output:

referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'Any' and 'String' be equivalent

This happens simply because the array is a one-dimensional array that has both numbers and arrays as its elements. It is no longer trivial to flatten the array as it is already flat but has some unflattened elements.

To fix the problem, you need to write a separate function that recursively flattens the deeply nested arrays of integers.

func recFlat(_ array:[Any]) -> [Int] {
    var flatenedArray: [Int] = []
    array.forEach {
        if let elem = $0 as? Int {
            flatenedArray.append(elem)
        }
        if let elem = $0 as? [Any] {
            let flattened = recFlat(elem)
            flattened.forEach { flatenedArray.append($0) }
        }
    }
    return flatenedArray
}

Output:

let arr = [[1, [2, 3]], [4, 5, [6]], [7, [8, [9]]]]
let flatData = recFlat(arr)

print(flatData)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Awesome. I hope you found out what you were looking for.

Thanks for reading.

Happy coding!

Further Reading

50 Swift Interview Questions

Resources for Developers

Share this article with others:

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email

Learn these 10 tips to write professional code.

 

Make your coding life easier with these amazing command-line tools

 

Learn how to use latest advancements in AI to write faster.