Flattening of multi level Array in Swift

Hi all! During interviews, from time to time the question comes up about how to align a multi-level array.

If this is a simple two-level array of the form [[1, 2], [3, 4]], then the standard higher-order function flatMap() will help us, although it is deprived, it is still available for use.

But what if we need to align more complex arrays, for example:

[1, [2]]-> [1, 2]

[1, [2, 3]]-> [1, 2, 3]

[1, [2, [3, [4]]]]-> [1, 2, 3, 4]

In this case, we can write our own recursive function:

func flattFunction(array:[Any]) -> [Int] {
    var flattenArray = [Int]()
    
    for element in array {
        if let element = element as? Int {
            flattenArray.append(element)
        } else if let element = element as? [Any] {
            let result = flattFunction(array: element)
            flattenArray += result
        }
    }
    
    return flattenArray
}

Let's test:

let arr1 = [1]
let arr2 = [1, 2, 3]
let arr3: [Any] = [1, [2]]
let arr4: [Any] = [1, [2, 3]]
let arr5: [Any] = [1, [2, [3, [4]]]]

func testFlattFunc() {
    print(flattFunction(array: arr1))
    print(flattFunction(array: arr2))
    print(flattFunction(array: arr3))
    print(flattFunction(array: arr4))
    print(flattFunction(array: arr5))
}

testFlattFunc()

// Вывод:
// [1]
// [1, 2, 3]
// [1, 2]
// [1, 2, 3]
// [1, 2, 3, 4]

I hope this little note will be useful.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *