Home > Software engineering >  Map an array of N strings to an array of arrays (of N/b strings)
Map an array of N strings to an array of arrays (of N/b strings)

Time:10-30

Say we have an array of strings, e.g.,

val arr1: Array[String] = Array("a", "b", "c", "d", "e", "f")

Is there any elegant way I can map this array to an Array of b arrays each? For simplicity, I guess it's possible to assume that b is divisible by the length of arr1.

For instance, the length of arr1 is 6, and for groups of b = 2, the result should be:

    Array( Array("a","b"), Array("c,d"), Array("e,f") )

Any strategies or hints are much appreciated!

CodePudding user response:

No strategies or hints required, there is a built-in function for this:

val b = 2;

arr1.grouped(b).toArray

If b is not a multiple of the array size then the last element will have fewer than b values. If the array is empty, the result is also empty.

  • Related