DEVus
Map, Filter And Reducer How These Higher Order Functions Works?
eulazzo

eulazzo

Feb 21,2022

Map, Filter And Reducer How These Higher Order Functions Works?

First of all, what's Higher Order Functions? basically Is a function that accepts another function by argument, returns a function or both. In JavaScript we have quite a few of these types of functions: element.addEventListener(type, handlerFunc), map, filter, reduce, sort etc. All of them are Higher Order Functions since they accept a function as an argument. (from now on I will call the Higher Order Function as HOF just for convenience ). But you can ask, what's the point of a function returning another function? Why is that so interesting?Well, we will get to that point later, but for now let's see the image below. We have these three functions, double, triple and quadruple the number passed as argument, but that's not a good idea because is a redundant code since only difference between them is for how much the number is multiplied by (2,3,4 etc) and they're not a HOF because doesn't return any function or accept it as argument.

HOF1.png

Instead of doing that way, we could simply do a function to return one of these multiplication functions. Now, as you can see below, getMultiplier is a HOF, because return a function and do not need a lot of functions for each case(triple,double, etc), looks a lot better doesn't it? Wait....So It's possible to use functions as values, assign functions themselves to variables, use them as arguments or even returns? YES! Since JavaScript functions are first-class citizens,  you can do that easily. What's happening on the code below is: In line 9, the  getMultiplier(2) invocation returns the function on line 3 to the variable double (line 9), now the double variable are the same double function before, that's happen with triple also, the number passed on getMultiplier(NUMBER) defines if will be triple, double, quadruple etc.

HOF2.png

Now let's talk about map, filter and reduce HOF.

1 - Map

map is a method available for arrays, and is a HOF because it accepts a function as argument. We should use the map when we want a array with the same quantity of items of the original array, but with each item different from before, just like the filter and reducer, map can accept 3 arguments on : The item, index and the array itself. The function inside of map, is executed for each item on the array you are working with, for example, given the following array how can we use map for multiply each number by 2 ?

HOF3.png

As we discussed above, the function inside of map is executed for each number of numbers array. First the number parameter is one, so one multiplied for 2 is equal to 2, since map create another array, the 2 is added on this new array, after that the same function is executed again with number parameter worth two and 2 multiplied by 2 is 4, so the result is added on the array created early and that happen until the last element on numbers array.

PS: map ALWAYS needs to return something, this is the main difference between map and forEach for example.

Now that we have the knowledge how map works, let's do another example: In this case we want an array but instead of that bunch of data such as category,start and end only with the company name. Because we want an array with the same numbers of elements but the items transformed, map is the one to be used.

HOF4.png

As output, companiesNames shows an array only with name value, something like ["Company One", "Company Two", ...,"Company Nine"].

2 - Filter

Just like map, filter is also a HOF because takes a function as argument. The callback is executed for every item on array. Unlike the map, the filter is used when you want, based on a condition, an array but this time only some of the items in the original array. Let's take a look at the age group below, the aim is to filter and get ages over 18 only. (If so, that means you can drink in Brazil).

HOF5.png

As i said before, filter callback accept 3 arguments: item, index and the array itself. On example above, the function is executed for each numbers on ages array. First age is equal to 11, so verify is 11 > 18, then go to the next as age equal to 14 and so on. When the age is greater than 18 that number is added on a new array created by filter. Basically the filter works like this, if a condition is true, the number is added to this new array. If all condition returns false, filter returns a empty array.

But... we can definitely make this canDrink function look more "attractive", can't we? First, could we use the arrow function, the brackets? we don't need them or the implicit return.

HOF5.png

Now it's more interesting. Okay...now that we know how this one works, let's do another example. This time, we have the same company object we works early with map. But now, we don't want an array with company names. Instead, we should get an array of only companies who have the "Retail" category, because there is a condition to choose which data should be added to the new array(and most probably with different length than the original array), filter is the one to be used.

HOF6.png

As output we get an array with two objects that satisfies the condition: Company One and Company Eight. Now let's understand how reduce works.

3 - Reduce

YES! as you should guessed, reduce is also a HOF, takes a callback as argument, and that function can accept 3 arguments: accumulator,Item, index and the array itself. The function is executed for each item. But when should you use these powerful method? Well, when you want to reduce a given array to some type of data(Object, string, number or array). The huge difference here, is that unlike filter or map, reduce can give us a created data different from array. As always let's see some example, to better understanding. The classic and easy example to understand the reduce, given a array of numbers, let's implement a function to reduce to give us a sum of all the numbers.

HOF7.png

On the first iteration, accumulator receive 0 and item the first number of numbers array, in this case: 1.

Then the function is executed, 0+1 = 1. This 1 value is assigned to accumulator. For the second time, accumulator now is equal to 1 and item 2, 1+2=3. The 3 value is again assigned to accumulator. The elements on numbers it's not finished yet, so the function executed again, now accumulator equal 3, item 3, 3+3 = 6. As you should figure it out by now, for the last time accumulator now is equal to 6 and item 4, 6+4 = 10. Then this value is assigned to the sumNumbers variable. The important thing to know, is that the callback inside of reduce always need to return something, and the accumulate is always received the value that executed early, the zero value basically we define a initial value to the accumulate. It's a good practice always define these value by doing that you know just by looking the type of data return from reduce. Let's do another example a bit more interesting this time. Like i said before, reduce can give us a data different from array, the image below we have an array with some Marvel movies, and we want a string in list format with all movies names. Because someMarvelMovies is an array and the final data is a string, reduce is the one to work with.

HOF8.png

On the first execution from the function inside reduce , accumulator is equal to empty string("") and name "Captain America: The First Avenger" as result a string with empty string, space, Captain America: The First Avenger. From second time, accumulate now is space, Captain America: The First Avenger and name "Captain America: The Winter Soldier" as result : space, Captain America: The First Avenger , Captain America: The Winter Soldier that will happen until the last of someMarvelMovies array. As result of reduce give us something like the output below.(/n was used to break a line)

HOF9List.png

So, that's it. We cover one of the most important methods on JavaScript.

4 - Where did I read about that before write it? 

Before I start to write all of this, I read the following articles :

1 - https://code.tutsplus.com/tutorials/how-to-use-map-filter-reduce-in-javascript--cms-26209

2 - https://www.w3schools.com/js/js_let.asp

3 - https://www.youtube.com/watch?v=bdLkAm12pgI

4 - https://dmitripavlutin.com/javascript-variables-best-practices/

5 - https://www.freecodecamp.org/news/javascript-map-reduce-and-filter-explained-with-examples/

eulazzo

eulazzo

Web Developer

Leave a Reply

Related Posts

Categories

;

DEVus

Copyrights © 2022. All Rights Reserved.Developed by @eulazzo