ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# mohamedali92's solution

## to Flatten Array in the Scala Track

Published at Sep 08 2020 · 0 comments
Instructions
Test suite
Solution

Take a nested list and return a single flattened list with all values except nil/null.

The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values.

For Example

input: [1,[2,3,null,4],[null],5]

output: [1,2,3,4,5]

The Scala exercises assume an SBT project scheme. The exercise solution source should be placed within the exercise directory/src/main/scala. The exercise unit tests can be found within the exercise directory/src/test/scala.

To run the tests simply run the command `sbt test` in the exercise directory.

Please see the learning and installation pages if you need any help.

## Source

Interview Question https://reference.wolfram.com/language/ref/Flatten.html

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### FlattenArrayTest.scala

``````import org.scalatest.{Matchers, FunSuite}

/** @version 1.2.0 */
class FlattenArrayTest extends FunSuite with Matchers {

test("no nesting") {
FlattenArray.flatten(List(0, 1, 2)) should be(List(0, 1, 2))
}

test("flattens array with just integers present") {
pending
FlattenArray.flatten(List(1, List(2, 3, 4, 5, 6, 7), 8)) should be(
List(1, 2, 3, 4, 5, 6, 7, 8))
}

test("5 level nesting") {
pending
FlattenArray.flatten(List(0,
2,
List(List(2, 3), 8, 100, 4, List(List(List(50)))),
-2)) should be(
List(0, 2, 2, 3, 8, 100, 4, 50, -2))
}

test("6 level nesting") {
pending
FlattenArray.flatten(List(
1,
List(2, List(List(3)), List(4, List(List(5))), 6, 7),
8)) should be(List(1, 2, 3, 4, 5, 6, 7, 8))
}

test("6 level nest list with null values") {
pending
FlattenArray.flatten(
List(0,
2,
List(List(2, 3), 8, List(List(100)), null, List(List(null))),
-2)) should be(List(0, 2, 2, 3, 8, 100, -2))
}

test("all values in nested list are null") {
pending
FlattenArray.flatten(
List(null,
List(List(List(null))),
null,
null,
List(List(null, null), null),
null)) should be(List())
}
}``````
``````object FlattenArray {
def flatten(input: List[Any]): List[Any] = {
input.flatMap {
case l: List[Any] => flatten(l)
case i: Int       => List(i)
case _            => List()
}
}
}``````