SidiAli
SidiAli

Reputation: 149

Reduce by key in an array of arrays in Scala

I've created an array in Scala

val L = Array((1,Array(one, two, one)), (2,Array(one, three, three)))

And I want to get this result:

  Array((1,(one,2), (two,1)), (2,(one,1),(three,2)))

I did

val LL = L.map({case (s, contents) => (s, contents.map(s=>(s,1)))})

and got

LL = Array((1,Array((one,1), (two,1), (one,1))), (2,Array((one,1), (three,1), (three,1))))

and I want to do a reduceByKey to have that result but it doesn't seem to work. Any help?

Upvotes: 1

Views: 1927

Answers (2)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Use foldLeft to iterate on each second value of the array item and count the occurrence of strings in each Array.

Scala repl

scala> val arr: Array[(Int, Array[String])] = Array((1, Array("one", "one", "two")))
arr: Array[(Int, Array[String])] = Array((1,Array(one, one, two)))

scala> arr.map { case (k, v) => k -> (v.foldLeft(Map.empty[String, Int])((r, c) => r.get(c).map(x => r.updated(c, x + 1)).getOrElse(r.updated(c, 1))).toArray) }
res16: Array[(Int, Array[(String, Int)])] = Array((1,Array((one,2), (two,1))))

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53859

Try:

L.map { case (key, values) => 
  (key, values.groupBy(identity).mapValues(_.size).toArray) 
}

Upvotes: 2

Related Questions