rcfrias
8/10/2017 - 4:22 PM

Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1

Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].

//: Playground - noun: a place where people can play

import Foundation

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

var myArray = [[1,2,[3]],4] as [Any]

func flatNestedArray(_ array: [Any]) -> [Int]{
    
    var newArray = [Int]()
    
    
    array.forEach { item in
        
        // check if its a number and if its an array get its children
        
        if let arr = item as? [Any] {
            
            newArray = newArray + flatNestedArray(arr)
        }
        else {
            newArray.append(item as! Int)
        }
        
    }
    
    return newArray
}

let myNewArray = flatNestedArray(myArray)