Scala nested flattening arrays

How to smooth an array of nested arrays of any depth?

for example

val in = Array( 1, Array(2,3), 4, Array(Array(5)) )

will be flattened onto

val out = Array(1,2,3,4,5)

Thanks at Advance.

+4
source share
1 answer

If you mixed Intand Array[Int], which is not very good for a start, you can do something like

in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai }

(it throws an exception if you put something else in your array). So you can use this as the basis for 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 do not know what you have in your nested arrays, you can replace the above Intwith Anyand get a flat one Array[Any]as a result. (Edit: The case Anymust be the last.)

(: , , .)

+9

Source: https://habr.com/ru/post/1536409/


All Articles