Dwight Lisper
Dwight Lisper

Reputation: 465

Scala: Array[Array[Int]] to Array[Int]

So I have an array of array of ints, for example

val n = Array(Array(1,2,3), Array(4,5,6), Array(7,8,9))

But I want to convert this to get Array(1,2,3,4,5,6,7,8,9)

Is that even possible and how? Thanks!

Upvotes: 1

Views: 847

Answers (3)

elm
elm

Reputation: 20435

The idiomatic flatMap / flatten is the way to go; yet you can implement the flattening for instance with a for comprehension as follows,

for (i <- n; j <- i) yield j

Upvotes: 0

Rok Kralj
Rok Kralj

Reputation: 48775

In addition to mushroom's answer:

If it is you who is producing such 2D array (as opposed to getting it from an external source), you might make use of a .flatMap function instead of two nested .maps.

Upvotes: 4

mushroom
mushroom

Reputation: 6289

You can use the flatten method. Calling n.flatten will output Array(1,2,3,4,5,6,7,8,9).

Upvotes: 8

Related Questions