Higher order functions: Map, Filter, and Reduce

Rinni Swift
4 min readNov 18, 2018

--

What are higher order functions?
Higher order functions are functions that take other functions as parameters or functions that return functions as a result.
Many functions… Let’s jump right in.

Map

Loops over a collection and applies the same operation to each element in the collection.
The return type is a generic array.

The map function has a single argument which is a closure. This closure is called every time it loops over the collection. Each element gets passed into the argument(closure) and returns a result; in this case, a generic array.

the below line 3 is using the shorthand syntax of closures using the $ operator

Let’s say we wanted to multiply all numbers in the array by 10 and we wanted to know all the name of the dishes in a restaurant:

// arrays
var numbers: [Int] = [2, 6, 22, 1, 19, 4]
numbers.map{ number in number * 10 }
numbers.map{ $0 * 10 }
// [20, 60, 220, 10, 190, 40]// dictionaries
var menu: [String: Int] = ["Sushi": 7, "Pad Thai": 13, "Curry": 15]
menu.map { (key, value) in key.uppercased() }
// ["Sushi", "Pad Thai", "Curry"]

Both return a generic array. (an array that can hold any type)

Can we get the index of each element while mapping?!
Yes indeed we could.

Let’s say we have an array of numbers from 1 to 5 and we want to know all the elements in it’s index. We would need to use the enumerate function to grab a sequence of pairs (n, x). n being an Int starting from 0 and x being an element of the sequence.

var numberArray = [1, 2, 3, 4, 5]
numberArray.enumerated().map { (index, element) in return “\(index):\(element)” }
// ["0:1", "1:2", "2:3", "3:4", "4:5"]

Filter

Loops over a collection and returns an array containing only elements that matched an include condition.
The return type is a filtered array

Let’s say we want all the even numbers in an array and we want all dishes that are more than $10:

// arrays
var numbers: [Int] = [2, 6, 22, 1, 19, 4]
let evenNumbers = numbers.filter{ $0 % 2 == 0 }
// [2, 6, 22, 4]// dictionaries
var menu: [String: Int] = ["Sushi": 7, "Pad Thai": 13, "Curry": 15]
menu.filter{ (key, value) in return value > 10}
menu.filter{ $1 > 10 }
// ["Pad Thai": 13, "Curry": 15]

remember that $0 is the key, and $1 is the value. This makes you able to access key, values in a dictionary by using the $ operator.

Reduce

Combines all values in a collection to a single value

Let’s say we want to add all numbers in an array, multiply all numbers in an array, combine all the strings in an array to one string, list all the dish names from a dictionary containing dish names and prices, and add all the prices of the dishes on the menu:

// arrays
var numbers = [3, 7, 22, 8, 15]
numbers.reduce( 0, { x, y in x + y })
numbers.reduce(0) { $0 + $1 }
numbers.reduce(0, +)
numbers.reduce(1, *)var strings = ["h", "a", "p", "p", "y"]
strings.reduce("", +)
// 55
// 55440
// happy
// dictionaries
var menu = ["Sushi": 7, "Pad Thai": 13, "Curry": 15]
menu.reduce("Famous dishes are: ") { (result, tupleOfKeyAndValue) in return result + tupleOfKeyAndValue.key + " " }
// the above code can be simplified to:
menu.reduce("Famous dishes are: "){ $0 + $1.key + " "}
menu.reduce("Famous dishes are: ") { $0 + $1.0 + " "}
menu.reduce(0) { (result, tupleOfKeyAndValue) in return result + tupleOfKeyAndValue.value }// Famous dishes are: Sushi Pad Thai Curry
// 35

For the number array, we give it 0 because we want the first number in the array to add 0 (x value) which once looped through another element, the updated value becomes the x value and keeps repeating until all items have been looped through the collection. With the x value being the return result.

For multiplying numbers, we put 1 instead of 0 because we want the first number to multiply by 1 to return it’s number instead of returning 0 as the value.

And for the reduce function on the dictionary above, it’s pretty straight forward. We want the key of the dictionary, in this case the dish name, to be appended to “Famous dishes are: ”. I created two pairs. (result, tupleOfKeyAndValue) result is the string(this will get updated every time it loops through the array) and tupleOfKeyAndValue is the tuple of current key-value pairs of the dictionary which in this case we want the dictionary’s key. and we add a space to the end of every item to make it more readable.

Remember, reduce on dictionaries takes in 2 arguments
1. an initial result of the type that should be reduced to
2. a tuple of current key-value pair.

Higher order functions improve the quality of your code! Now that you know about map filter and reduce more, I hope you remember this article and use higher order functions to implement into your code.

Thank you for studying with me! 👏
If you found this useful, please drop a share and some claps! 😄
All and any feedback is accepted. 😃

--

--

Rinni Swift

iOS engineer at PayPal and I write stories — Join me on my journey. 📍San Francisco, CA