3

I have two Array like this:

val l1 = Array((1,2,3), (6,2,-3), (6,2,-4))
val l2 = Array("a","b","c")

I would like to put values of l2 in array at the same position in l1 and obtain a final array like that

Array((1,2,3,"a"), (6,2,-3,"b"), (6,2,-4,"c"))

I was thinking about something like:

val l3 = l1.map( code...)

But i don't know how to iterate on l2 during map on l1.
Do you have any idea?

2 Answers 2

6

Combining collections in this way can be done with Zipping.

l1.zip(l2).map{ case (x,y) => (x._1, x._2, x._3, y) }
Sign up to request clarification or add additional context in comments.

Comments

1

You'll want to map over the indexes used to access elements from each array.

(0 until l1.length).map{ idx =>
  (l1(idx)._1, l1(idx)._2, l1(idx)._3, l2(idx))
}
res0: IndexedSeq[(Int, Int, Int, Char)] = Vector((1,2,3,a), (6,2,-3,b), (6,2,-4,c))

3 Comments

Thank you very much
You should use l1.indices instead of (0 until l1.length) to prevent off-by-one errors.
@corvus_192, an excellent suggestion, but marios still has the better solution.

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.