score:4

Accepted answer

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))

score:1

also for

val a = array("1", "2", "3")
val b = array("orange", "apple", "grape")
val c = array("milk", "juice", "cream")

then

(a,b,c).zipped.map{ case(x,y,z) => array(x,y,z) }

delivers

array(array(1, orange, milk), array(2, apple, juice), array(3, grape, cream))

update

yet a different approach to those using zippers, simpler

array(a,b,c).transpose

this allows for any number of input arrays, in contrast to zipper approachers which requires a priori knowledges of the number of input arrays for pattern-matching.


More Query from same tag