user3658637
user3658637

Reputation: 95

How to generate all possible key-value combinations between a String and Array[String]

I am very new to Scala and hence this might be a very basic question.

I have a variable "myArray" of type Array[(String, Array[String])]. The value of this array is

Array((1,Array(2, 3, 4)), (2,Array(1, 3, 4, 6, 7)), (3,Array(1, 2, 4, 5))). 

If we think the first element for each tuple is a key ( e.g., in the tuple (1,Array(2, 3, 4)), 1 is the key) and rest is the value (e.g., Array(2, 3, 4)), I want to create an Array for which the elements will be all possible combination of key-value pairs for each corresponding key, where the value will be each element of the Array[String]

The result should look like

Array((1,Array(1,2)), (1,Array(1,3)), (1,Array(1,4)), (2,Array(2,1)), 
      (2,Array(2,3)), (2,Array(2,4)), ...., (3,Array(3,4)), (3,Array(3,5)))

Upvotes: 0

Views: 877

Answers (2)

Gangstead
Gangstead

Reputation: 4182

@wingedsubmariner is close, but in order to match @user3658637's weird requirements the mapping is:

for {
  (key, values) <- array
  value <- values
  yield (key,Array(key, value))     //> res1: Array[(Int, Array[Int])] = Array((1,Array(1, 2)), (1,Array(1, 3)), (1,
                                    //| Array(1, 4)), (2,Array(2, 1)), (2,Array(2, 3)), (2,Array(2, 4)), (2,Array(2,
                                    //|  6)), (2,Array(2, 7)), (3,Array(3, 1)), (3,Array(3, 2)), (3,Array(3, 4)), (3
                                    //| ,Array(3, 5)))

Upvotes: 2

wingedsubmariner
wingedsubmariner

Reputation: 13667

If your array is in a value array:

for {
  (key, values) <- array
  value <- values
} yield (key, value)

Upvotes: 1

Related Questions