Map and filter functionality using reduce - Swift

Reduce is defined as below:

Returns the result of combining the elements of the sequence using the given closure.

Can we form the result of a map/filter function using reduce?

Yes.

Reduce function takes a sequence as an input and returns a generic output not. By setting the appropriate initial result and closure function we can exploit the reduce function to return another sequence instead of a single value result.

Reduce function as a map

let numbers1 = [1, 2, 3, 4]
let numberSum1 = numbers1.reduce([], { x, y in
    return x + [2*y]
})
print(numberSum1)

Result

[2, 4, 6, 8]

Reduce function as a filter

let numberSum2 = [1, 2, 3, 4].reduce([], { x, y in
    return x + ((y % 2 == 0) ? [y] : [])
})

print(numberSum2)

Result

[2, 4]

Article that inspired me to write this post: swiftunboxed.com/lang/reduce