Scala nested arrays flattening

2019-05-07 07:58发布

问题:

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.

回答1:

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 Ints 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.)