Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala nested arrays flattening

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.

like image 229
elm Avatar asked Jan 11 '23 19:01

elm


1 Answers

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

like image 112
Rex Kerr Avatar answered Jan 13 '23 08:01

Rex Kerr