How to flatten an array of nested arrays of any depth ?
For instance
val in = Array( 1, Array(2,3), 4, Array(Array(5)) )
would be flattened onto
val out = Array(1,2,3,4,5)
Thanks in Advance.
If you have mixed Int
and Array[Int]
, which is not a very good idea to begin with, you can do something like
in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai }
(it will throw an exception if you've put something else in your array). You can thus use this as the basis of a recursive function:
def flatInt(in: Array[Any]): Array[Int] = in.flatMap{
case i: Int => Array(i)
case ai: Array[Int] => ai
case x: Array[_] => flatInt(x.toArray[Any])
}
If you don't know what you've got in your nested arrays, you can replace the above Int
s by Any
and get a flat Array[Any]
as a result. (Edit: the Any
case then needs to go last.)
(Note: this is not tail-recursive, so it can overflow the stack if your arrays are nested extremely deeply.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With