1

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!

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Yes, and mb it will be useful, flatten can be written as a flatMap(identity).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.