Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat two Scala Array

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?

like image 954
a.moussa Avatar asked Jan 17 '26 23:01

a.moussa


2 Answers

Combining collections in this way can be done with Zipping.

l1.zip(l2).map{ case (x,y) => (x._1, x._2, x._3, y) }
like image 160
marios Avatar answered Jan 19 '26 16:01

marios


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))
like image 36
jwvh Avatar answered Jan 19 '26 16:01

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!