How do I convert a nested array to a flat array?

I have a nested array: Array("AA", Array("BB", "CC"), "DD")

. How can I convert it to: Array("AA", "BB", "CC", "DD")

in Scala?

Thanks for the help!

+3


source to share


4 answers


First of all, check the inferred type of the array:

scala> val arr = Array("AA", Array("BB", "CC"), "DD")
arr: Array[java.io.Serializable] = Array(AA, Array(BB, CC), DD)

      

Scala collections have one type of its elements, so if you put in the array as a string, and an array of strings (or array is an array of strings), you get an array of element type, which is the most typical type of shared how String

, as well as Array[String]

- in this case Serializable

, which is pretty useless, because in order to do anything with the elements of the array, you have to give them some other type.

So it's best not to get into this situation in the first place. You get a lot more miles from the type system if you don't mix unrelated things in collections. However, if you need it, you can write something like this:

def flattenStringArrays[A](arr: Array[A]): Array[String] =
  arr.flatMap {
    case s: String => Array(s)
    case a: Array[_] => flattenStringArrays(a)
  }

      



And then:

scala> flattenStringArrays(arr)
res0: Array[String] = Array(AA, BB, CC, DD)

      

Or, if you "know", you will only have one nesting level:

scala> arr.flatMap {
     |   case s: String => Array(s)
     |   case a: Array[String] => a
     | }
res1: Array[String] = Array(AA, BB, CC, DD)

      

But both of them are unsafe and really uniiomatic.

+2


source


array.flatMap {
    case x: Array[_] => x
    case y => List(y)
}

      



0


source


Here's my version using foldLeft and some pattern matching: (It doesn't preserve the original order)

$ scala
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala>   val container = Array("AA", Array("BB", "CC"), "DD")
container: Array[java.io.Serializable] = Array(AA, Array(BB, CC), DD)

scala>   container.foldLeft(Array.empty[String]) { (memo, next) =>
     |     next match {
     |       case s: String => s +: memo
     |       case arr: Array[_] => arr.map(_.toString) ++ memo
     |     }
     |   }
res0: Array[String] = Array(DD, BB, CC, AA)

      

-1


source


Loop through the nested array and add all the elements inside any nested array to a new flat array. then remove the nested arrays and add the newly created array.

In the example given. Loop through the array and you find a nested array containing "BB" and "CC", so add "BB" and "CC" to the new array (call array2). Then remove the array containing "BB" and "CC" from the original nested array. Then add array2. Hope it helps

-4


source







All Articles