In Scala, how to group consecutive elements in an array

Considering

scala> val a = (1 to 9).toArray
a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)

would thus be grouped elements a,

Array(Array(1,2,3), Array(4,5,6), Array(7,8,9))
+3
source share
1 answer

If you want to get groups of 3 elements, you can use the method grouped:

a.grouped(3).toArray
// Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
+13
source

All Articles