Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one flatten an array of arrays in Scala?

Tags:

scala

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

like image 831
lserlohn Avatar asked Feb 16 '18 19:02

lserlohn


People also ask

How does flatten work in Scala?

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.

What does it mean to flatten an array?

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.


3 Answers

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

like image 76
Jordan Cutler Avatar answered Sep 17 '22 04:09

Jordan Cutler


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
like image 29
Euge Avatar answered Sep 17 '22 04:09

Euge


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.

like image 40
Alvaro Carrasco Avatar answered Sep 18 '22 04:09

Alvaro Carrasco