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([]) { $0 + $1 }
}

let aTwoDimArrayOfNumbers = [[1, 3, 5],[2, 4, 6]]
let flatMappedArray = flatMapIntermsOfReduce(elements: aTwoDimArrayOfNumbers) { $0 }

The flatMappedArray will be [1, 3, 5, 2, 4, 6].