Map, Reduce and Filter: The Saviour Guide🎯

Map, Reduce and Filter: The Saviour Guide🎯

Introduction

Well in JavaScript, there are arrays and there are methods. They exist to make the life of programmer and developers a bit easy. These array methods - map, reduce and filter have some interesting applications and usecases in the JavaScript programming world. In this blog, we will see the modus operandi of these methods with code examples to help you better visualize its interpretations.

Some bits about Arrays🔨

The eternal line in JavaScript is "Everything in JavaScript is object.

Well about objects and some basic array operations and methods, I already have a separate blog dedicated to that particular topic where we talked some of the fundamental differences between arrays and objects and, in particular, array methods in details.

But to set the preface or sort of some bare minimum introduction to the blog, it would be better to understand some bits and pieces of array first.

So, array is nothing but an object in JavaScript that organizes data in an orderly manner, nothing fancy here, just like other arrays in "traditional" languages but with the freedom of storing duplicate values, of multiple data types and some other privileges that it enjoys being a part of a dynamically typed language.

We can loop through an array, search via indexing, pop, push, shift, unshift and perform literally every operations that what other languages provide in their arrays. But in JavaScript, we have some special methods that are somewhat unique to the JavaScript paradigm. And these are, as the blog title suggests, map, reduce and filter.

Let's see what these are in details one by one.

Map

So, map() is an inbuilt method of array. When called upon an array, it actually returns a new one with elements modified by the callback function that is passed as the parameter in the map function. I know by simply reading this, the function does not seem to digest once. So it would be better if we see the actual functioning of the method with coded examples.

let arr = [1, 2, 3, 4, 5];
let modifiedArr = arr.map(element=>{
    return element*2
});
console.log(modifiedArr);

With the above code things start getting a tiny bit easier. Now let us see line by line, what we are doing in the above example. First of all, we need to define the array and initialize it with some values, that we did in the first line itself.

Remember one thing, I told you that map() returns a new arr, so to be able to log out the new array result, we first need to save this one into a variable, that is what we are doing in the second line with modifiedArr and after creating the variable we are assigning it the values that are returned by the map method.

One interesting that lies inside the method scope of map is the underlying callback function. A callback function is nothing but a function that is passed to another function, in our case map(), as a parameter. It takes a parameter that is nothing but the element of the original array, in this case, we are using element keyword itself for the purpose. The callback function will perform the operation defined in the function statement on each element of the original array and will save the output in the new modified array in the same order. As simple as that.

So, basically we are picking up elements from the array one by one, performing some actions on them and putting the result into a new array.

Stop! stop!!, we do the same thing in 'forEach()', don't we?. Well, not exactly. forEach() method does not return a new array and the return type of it is undefined unlike map(), where return is defined as per the result and also, it creates a new array.

That's all about map(), let's see what filter() does?

Filter

As we saw in the map method, we traverse through each element and returns a corresponding element after some actions performed on it. But what if we don't need all the values being returned? If we want only some value to be returned that pass certain conditions. In this situation, filter method comes to our rescue.

So, what filter will do is it will simply "filter" out results that are not truthy, i.e., does not pass mentioned conditions. Let's us understand this from below example.

let arr = [1,2,3,4,5];
let modifiedArr = arr.filter(element=>{
    if(element%2===0){
        return true;
    };
    return false;
})
console.log(modifiedArr); // [2,4]

In above example, we intend to filter out all the odd integers and keep only even integers in the new array. So we are passing a callback with element as a parameter to check if the integer is even or not. This is done using the conventional method of taking the modulus of the interger with 2, it it produces 0, then it is even, hence we return true, otherwise false.

Note that filter method will only "filter" in those elements that coerces to true.

Reduce

Here comes the most intriguing and confusing method of the three, that is, reduce(). I advise you not to think this particular method in the manner we were thinking about map() and filter(). Its execution and use-cases are somewhat unique and fascinating.

Before moving forward, it is important to understand the code syntax of this method and henceforth, we will build forth the concept around it. So, let's see the syntax:

reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;

In the above syntax, think of T as a datatype like number or string.

So, let us understand the reduce method properly: reduce() method will take two parameters

  • callback function
  • initial value (if necessary)

For callback function, it can accept maximum four arguments. This callback function is called for each element of the array. Its first argument previousValue is nothing but the accumulator that accumulates the return value of the function for each iteration. currentValue indicates the element of the array in that particular iteration. currentIndex as the name suggest indicates the current index of the element in the iteration.

Whereas, initialValue argument if provided, becomes the first iteration value of the accumulator.

Let us look at the common illustration of the reduce method by returning the sum of all elements of array.

let array = [1,2,3,4,5];
const result = array.reduce((p, c)=>{
    console.log("p:",  p, "c:", c );
    return p+c;
}, 0);
console.log(result); // 15

In the above program, we using accumulator or previousValue as p and currentValue as c as the arguments of the callback function. If you look carefully, we are logging the p and c values for each iteration to the console. After the callback function, we have provided the initial value for p for first iteration as 0. Afterwards the first iteration, the value of p would be the return value of the callback function.

Carefully observe the values of p and c.

resul-pc.png

The return value of the final iteration would be the final return value of the method and hence will be the result.

That's all about the beast methods of Arrays. In this blog, I have covered about the methods in greater details and these are all enough to get started. I would advise you to code the examples hands-on to properly understand the nuances.

I have referred to the MDN Web Docs for this blog.

Happy Learning

#iwritecode #lco #webdev #javascript

`