a.moussa - 1 year ago 98
Scala Question

# Groupby Array[Array[String]] Scala

I have an Array[Array[String]] like this:

``````Array(Array("A","1","2"),
Array("A","3","4"),
Array("A","5","6"),
Array("B","7","8"),
Array("B","9","10"))
``````

I would like to groupby on the first element of each sub Array and get a Map like this:

``````var A:Map[String, Array[String] = Map()
A + = ('A' -> Array("1", "2"))
A + = ('A' -> Array("3", "4"))
A + = ('A' -> Array("5", "6"))
A + = ('B' -> Array("7", "8"))
A + = ('B' -> Array("9", "10"))
``````

I don't know how to manipulate groupby to get this result.

Do you have any idea?

Try this.

``````val arr = Array(Array("A","1","2"),
Array("A","3","4"),
Array("A","5","6"),
Array("B","7","8"),
Array("B","9","10"))

val result = arr.groupBy(_.head).map{case (k,v) => k -> v.flatMap(_.tail)}

result("A")  // Array(1, 2, 3, 4, 5, 6)
result("B")  // Array(7, 8, 9, 10)
``````

Basically, after grouping you need to remove the head of each sub-array (that's the `tail` part), and you need to flatten the sub-arrays into a single array (that's the `flatMap` part).

Warning: this will throw a runtime exception if any of the sub-arrays are empty. Here's a version that will take care of that.

``````val result=arr.groupBy(_.headOption).collect{case (Some(k),v)=>k->v.flatMap(_.tail)}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download