4

suppose I have two arrays

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

what's the most elegant way to get a new array like ["one1","two2","three3"]

1
  • yes ,it's very helpful Commented Mar 19, 2015 at 8:04

3 Answers 3

13

Using zip and map should do it:

(x zip y) map { case (a, b) => a + b }
Sign up to request clarification or add additional context in comments.

Comments

3

Similarly to @m-z, with a for comprehension, like this,

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

This can be encapsulated into an 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)

Comments

0

As alternative to zip:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.