Feynman27 Feynman27 - 1 year ago 142
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 Source
scala> arr.zip(mask).collect { case (v, true) => v }
res0: Seq[String] = List(A, C)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download