0

I have an Array[String] in scala like this

my_array: Array[String] = Array(RED;BLUE, RED;PINK, RED;ORANGE, RED;WHITE, RED;YELLOW, 
RED;GREY,GREEN;BLUE, GREEN;PINK, GREEN;BROWN, GREEN;ORANGE, GREEN;WHITE, GREEN;YELLOW, GREEN;GREY)

and I need to get this result

my_new_array: Array[Array[String]] = Array(Array(RED;BLUE, RED;PINK, RED;ORANGE, RED;WHITE,RED;YELLOW, RED;GREY), 
Array(GREEN;BLUE, GREEN;PINK, GREEN;BROWN, GREEN;ORANGE, GREEN;WHITE, GREEN;YELLOW, GREEN;GREY), 
Array(RED;BLUE, GREEN;BLUE), Array(RED;PINK, GREEN;PINK), 
Array(RED;ORANGE, GREEN;ORANGE), Array(RED;WHITE, GREEN;WHITE),    
Array(RED;YELLOW, GREEN;YELLOW), Array(RED;GREY, GREEN;GREY))

These should be te steps

  • get a list of unique colors. this means I have to split by ";" each string
  • once I have this list I have to create a new Array contained the original strings grouped by each single color

Does anyone have an hint?

0

1 Answer 1

5

Provided I've understood your question correctly, this should work (probably not the most efficient solution ever)

myArray
.flatMap(_.split(';'))                      // get all the colors
.distinct                                   // get the unique set of colors
.map(color => myArray.filter(_.contains(color)))  // map each color to each group containing it

I'm using contains assuming that for "YELLOW" you want to match both "YELLOW";"RED" and "RED";"YELLOW".

In case you want to match only the former, you can use startsWith intead.

Sign up to request clarification or add additional context in comments.

1 Comment

x should be myArray in the last map statement. x does not exist.

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.