Data Transformations - Map, Filter & Reduce
The tools I'm talking about are: map, filter, and reduce. In this lecture, I'm just going to give you a quick overview of them. Then, over the next couple of lectures, we will deep dive into these three methods in practice so we can use them throughout the rest of the course.
The map method is yet another method that we can use to loop over arrays. It is similar to the
forEach method we studied before, but with the difference, that map creates a new array based on the original one. So essentially, the map method takes an array, loops over that array, and in each iteration, it applies a callback function that we specify in our code to the current array element.
From the above image, each element of the original array is multiplied by two. That is, with the callback function in place, the map method multiplies every single element by two and puts it into a new array. We say that it maps the values of the original array to a new array, and that's why this method is called map.
This method is extremely useful. Usually way more useful than the
forEach method because
forEach allows us to do some work with each array element. But map, on the other hand, builds us a brand new array containing the results of applying an operation to the original array.
As the name says, the filter method filters for elements in the original array that satisfy a certain condition.
In the above example, we are only looking for elements greater than two. So all the elements that pass the specified test will make it into a new filtered array. Or in other words, elements for which the condition is true will be included in a new array that the filter method returns. All other elements will get filtered out. i.e., they will not be included in the new array.
Finally, there is the reduce method that we use to boil down all the elements of the original array into one single value. There are many interesting things we can do with the reduce method. An example is to add all the elements of an array together.
In other to achieve this, we need to specifiy an accumulator variable. Then as the reduce method loops over the array, it keeps adding the current element onto the accumulator until, at the end of the loop, we have the total sum of all the elements. You can imagine this as a snowball. It keeps getting bigger and bigger as it rolls down a hill. And so this is known as the snowball effect, and reduce is pretty similar to that. So keep that in mind as a nice analogy.
Now we also said that this whole process reduces the original array to one single value, which in this case is the sum of all the elements, but it can, of course, be many other operations. And the returned value is the reduced value. So there is no new array in this case—only the reduced value.
All these methods probably sounds more complicated than it actually is. Hence, let's start to put it into practice right in the next lecture starting with the map method.