Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging Arrays in scala

Tags:

scala

I have 3 Array

Array("1", "2", "3")

Array("orange", "Apple", "Grape")

Array("Milk", "juice", "cream")

on merging I need to output as

Array( Array("1", "orange", "Milk"), Array("2", "Apple", "juice"), Array("1", "Grape", "cream") )

Is this possible with Scala built in functions?

like image 249
BalaB Avatar asked Feb 03 '26 18:02

BalaB


1 Answers

As long as your arrays have the same length, this can be accomplished using zip and map

Define arrays

scala> Array("1", "2", "3")
res0: Array[String] = Array(1, 2, 3)

scala> Array("orange", "Apple", "Grape")
res1: Array[String] = Array(orange, Apple, Grape)

scala> Array("Milk", "juice", "cream")
res2: Array[String] = Array(Milk, juice, cream)

zip them together in two steps. zip creates arrays of tuples

scala> res0 zip res1
res3: Array[(String, String)] = Array((1,orange), (2,Apple), (3,Grape))

scala> res3 zip res2
res4: Array[((String, String), String)] = Array(((1,orange),Milk), ((2,Apple),juice), ((3,Grape),cream))

map over the zipped result to transform the nested tuples to Arrays

scala> res4 map {case ((a,b),c) => Array(a,b,c) }
res5: Array[Array[String]] = Array(Array(1, orange, Milk), Array(2, Apple, juice), Array(3, Grape, cream))
like image 105
rompetroll Avatar answered Feb 05 '26 08:02

rompetroll



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!