Skip to content

Instantly share code, notes, and snippets.

@rcfrias
Last active August 10, 2017 16:23
Show Gist options
  • Save rcfrias/73001893340e1612f88d4f140056372e to your computer and use it in GitHub Desktop.
Save rcfrias/73001893340e1612f88d4f140056372e to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment