paint-brush
Map⇄Filter⇄Reduce↻by@ashaymurceilago
7,989 reads
7,989 reads

Map⇄Filter⇄Reduce↻

tldt arrow

Too Long; Didn't Read

Due to that reason we were introduced with these three <em>higher order functions</em>, namely 🗺️Map, 🥅Filter &amp; ✂️Reduce.

Company Mentioned

Mention Thumbnail
featured image - Map⇄Filter⇄Reduce↻
Ashay Mandwarya 🖋️💻🍕 HackerNoon profile picture

For loops are messy!

Share it on LinkedIn!

Due to that reason we were introduced with these three higher order functions, namely 🗺️Map, 🥅Filter & ✂️Reduce.

But before going into the functions, let’s clear out what are higher order functions and Functional Programming.

Photo by Roman Mager on Unsplash

Functional programming?

Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data — Wikipedia

Photo by Yeshi Kangrang on Unsplash

Higher Order Functions

Higher order functions are functions that that takes other functions as arguments or return them. In simple words, if a function is returning another function or taking a function as an argument to operate upon, than that function is called a Higher Order Function.

All of the map, filter and reduce operate upon arrays but behave very differently.

Let’s dive in!

Array.prototype.map() || map() || 🗺️

The **map()** method creates a new array with the results of calling a provided function on every element in the calling array → MDN

Photo by Capturing the human heart. on Unsplash



var arr = [5, 7, 4, 12];let map = arr.map(x => x * 7);console.log(map);

The above codes takes in each element of the array ,multiplies it with 7 and puts it in a new array(done by map internally)

the same with a for loop








var arr = [5, 7, 4, 12];var map=[];var i=0;for(i=0;i<arr.length;i++){map.push(arr[i]*7)}console.log(map);

From 3 lines we directly went to 7 lines of code, which is more than double.

map calls a provided callback function upon each element in the array and constructs a new array from the results. callback is called only for indexes for which the array contains a value.

map builds a new array and never changes/mutates the old one, it just iterates over the old array, but the mutation can be done if the callback is programmed to do so.

When the map function starts iterating over the array a range which is the length of the array is set and if new elements are added to the array during this time, map won’t access them.

Let’s dissect it-

Parameters- The parameters taken by the map function is a callback function which in turn takes parameters currentValue, index & array.

  • currentValue→ It is the current element which is processed by the map.
  • array|_optional_→The array on which the map was called upon.
  • index|_optional_→ The index of the current element which is being processed in the array.

Return-

map returns a new array with the values processed by the callback.

Array.prototype.filter() || filter() || 🥅

The **filter()** method creates a new array with all elements that pass the test implemented by the provided function→MDN

Photo by Wade Austin Ellis on Unsplash



var cars = ['Mclaren','Lamborghini','Ferrari','Porsche','Mercedes','Corvette'];let car = cars.filter(e => e.length > 7);console.log(car);

The above codes takes in each element of the array, checks if the element length is greater then 7 and puts it in a new array(done by filter internally)

the same with for loop.








var cars = ['Mclaren','Lamborghini','Ferrari','Porsche','Mercedes','Corvette'];let car=[]for(let i=0;i<cars.length;i++){if(cars[i].length>7)car.push(cars[i]);}console.log(car);

From 3 lines to 8 lines

filter calls a provided callback function upon each element in the array and constructs a new array from the results. callback only returns the value which satisfy the condition or in other words is evaluated to true. callback is called only for indexes for which the array contains a value.

filter builds a new array and never changes/mutates the old one, it just iterates over the old array.

When the filter function starts iterating over the array a range which is the length of the array is set and if new elements are added to the array during this time, filter won’t access them.

Let’s dissect it-

Parameters- The parameters taken by the filter function is a callback function which in turn takes parameters currentValue, index & array.

  • currentValue→ It is the current element which is processed by the filter.
  • array|_optional_→The array on which the filter was called upon.
  • index|_optional_→ The index of the current element which is being processed in the array.

Return-

filter returns a new array with the true values processed by the callback.

Array.prototype.reduce() || reduce() || ✂️

The **reduce()** method executes a reducer function (that you provide) on each member of the array resulting in a single output value→MDN

Photo by Plush Design Studio on Unsplash




const arr = [3, 4, 2, 9];const reduce=(accumulator, currentValue)=>accumulator+currentValue;console.log(arr.reduce(reduce));console.log(arr.reduce(reduce, 7));

In the above code, we create a reduce function which will be passed as a callback to the .reduce() function. The function returns the addition of all the elements in the array. The accumulator stores the sum of the elements after every iteration and currentValue represents the value currently processed. The default value of the accumulator is 0 and can also be user defined as done in the second console.log as 7. The accumulator is returned as a final result.

with for loop








const arr = [3, 4, 2, 9];var a=0;for(leti=0;i<arr.length;i++){a+=arr[i];}console.log(a);

From 3 lines we go to 7 lines.

reduce calls a provided callback function upon each element in the array and is called only for indexes for which the array contains a value.

The callback is given 4 arguments

  • accumulator
  • currentValue
  • currentIndex
  • array

The first time when the callback is called just before processing the first value the currentValue will be the first element in the array while the accumulator will have the value of the first element of the array or the value which is specified by the user in the reduce function.

If the accumulator is provided a value then reduce will start the callback from index 1 and skip the first index as accumulator already has the value of the first index. If initially the value is provided the callback will start from the first index.

The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(), then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

If the array is empty and no initial value is given to the accumulator, a TypeError is thrown.

It is usually safer to provide an initial value because there are three possible outputs without initialValue, as shown in the following example.

Let’s dissect it-

Parameters- The parameters taken by the reduce function is a callback function which in turn takes parameters accumulator, index, array & currentValue.

  • currentValue→ It is the current element which is processed by the reduce.
  • array|_optional_→The array on which the reduce was called upon.
  • index|_optional_→ The index of the current element which is being processed in the array.
  • **accumulator|**optional→ Value to use as the first argument on the first call of the callback.

Return-

reduce returns the value left after reduce is done(accumulator).

Chaining .map(), .reduce(), and .filter() || 🗺️🥅✂️

As we have seen reduce, filter and map are quite powerful on their own, but the cherry on top of the cake is that they all work on arrays and thus can be chained together.

Photo by Katherine Chase on Unsplash

Let’s take an example-





















var cars = [{name: "Lamborghini",maxSpeed:320,beauty:99},{name: "Lamborghini",maxSpeed:340,beauty:99},{name: "Ferrari",maxSpeed:310,beauty:99},{name: "Porsche",maxSpeed:330,beauty:99},{name: "Lamborghini",maxSpeed:300,beauty:99}];

The above is the data we will be working with. We have to find the total score of all the Lamborghini’s.

Its a one liner-

Result-

With a for loop we had to create 3 loops which will be quite a mess.

The code works like-

  • filter- The filter finds all the cars whose name is Lamborghini.

  • map- The map works on the array returned by the filter and sums up the beauty and top_speed properties.

  • reduce- reduce takes the array returned by the map and sums all the values thus returning the total of all the lamborghini.

Conclusion

Hope I made the functions quite understandable. Chaining all the 3 functions together makes this a monster as we get our results with writing clean code which is small in length and easy to debug.

Clap & Follow.

Google