Atharva Vaidya     About     Archive     Feed

Map, Filter and Reduce

What are they? They are functions that take functions as an argument.

Map

Map is used to transform the elements in an array or set. Say you want to multiply each element in an array by 2. How would you do this using a for-loop?

for i in 0 ..< array.count { array[i] *= 2 } 

This is how you would do the same using a map function on the array:

let newArray = array.map({$0 * 2}) 

Now, what’s the big difference here? Map evaluates the statement inside those curly braces and assigns that value to the corresponding element in the array.

Filter

Say you want to remove all numbers below 100 from an array. How would you do this using a for loop?

var filteredArray: [Int] = []
for i in array 
{
  if i >= 100 { filteredArray.append(i) }
}

This is how it is done using filter:

let filteredArray = array.filter({$0 >= 100})

Boom! Just one line of code and done.

Reduce

Say you want to get the mean of all elements in an array. You know how you would do it with a for loop, so I’ll skip to the reduce implementation.

let array = [2.2, 1.2, 2.4, 5.5, 7.8]

let mean = array.reduce(0, +) / Double(array.count)

The first argument in the funtion is the initial element and the second argument is a function that specifies how to combine two elements. Since + is a funtion in swift we don’t even need to write {$0 + $1}