## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# The flatMap function in terms of reduce

To understand the power of reduce, we can implement the flatMap function in terms of reduce as well:

```func flatMapIntermsOfReduce<Element>(elements: [Element], transform: (Element) -> Element?) -> [Element] {   return reduce(elements: elements, initial: []) {         guard let transformationResult = transform(\$1) else {             return \$0         }         return \$0 + [transformationResult]     } } let anArrayOfNumbers = [1, 3, 5] let oneDimensionalArray = flatMapIntermsOfReduce(elements: anArrayOfNumbers) { \$0 + 5 }
```

Also, we can flatten a two-dimensional array using the reduce method as follows:

`func flatMapIntermsOfReduce<Element>(elements: [[Element]], transform: (Element) -> Element) -> [Element] {  return elements.reduce([]) ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required