Feynman27 Feynman27 - 2 months ago 27
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?

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