Feynman27 Feynman27 - 4 months ago 43
Scala Question

Apply boolean mask to Scala array

I'm trying to use an array of booleans to choose particular elements in another array. For example:

val arr = Seq("A", "B", "C")
val mask = Seq(true,false,true)

and I'd like the output to be a new array:

val arr_new = Seq("A","C")

Is there a way to achieve this in Scala?

scala> arr.zip(mask).collect { case (v, true) => v }
res0: Seq[String] = List(A, C)