How to join two arrays: scala

suppose i have two arrays

val x =Array("one","two","three")
val y =Array("1","2","3")

what is the most elegant way to get a new array, like ["One1", "two2", "three3"]

+4
source share
3 answers

Use zipand mapshould do this:

(x zip y) map { case (a, b) => a + b }
+13
source

Like @mz, with an understanding like this,

for ( (a,b) <- x zip y ) yield a + b

It can be encapsulated in implicit, such as

implicit class StrArrayOps(val x: Array[String]) extends AnyVal { 
  def join(y: Array[String]) = 
    for ( (a,b) <- x zip y ) yield a + b 
}

and use it like this:

x join y
Array(one1, two2, three3)
+3
source

Alternatively zip:

(0 until math.min(x.length, y.length))
          .map(i => x(i) + y(i))
          .toArray
0
source

All Articles