I have the following array:
val input = Array(Array(), Array(22,33), Array(), Array(77), Array(88,99))
It contains empty arrays. I want to get a flattened array without any empty arrays, so the output should be:
Array(22,33,77,88,99)
I tried the flatten
function, but it seems to not work with the type of Array[_ <: Int]
.
The flatten function is applicable to both Scala's Mutable and Immutable collection data structures. The flatten method will collapse the elements of a collection to create a single collection with elements of the same type.
Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.
Another way of writing:
input.flatMap(_.toList)
The empty arrays get converted to Nils and since it's a flatMap the Nils get flattened out
Monads are your friends:
for { a <- input; b <- a.toList } yield b
Edit:
If you specify the type, flatten
works fine
val input: Array[Array[Int]] = Array(Array(), Array(22,33), Array(), Array(77), Array(88,99))
input.flatten
It's inferring Array[_ <: Int]
because some of the arrays are empty. Try this:
val input = Array(Array[Int](), Array(22,33), Array[Int](), Array(77), Array(88,99)).flatten
That ensures that the resulting type is Array[Array[Int]]
which should be flattenable.
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