Last active
August 10, 2017 16:23
-
-
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].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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