filter() – Javascript Functional Programming

Previously, we have explored map() in JavaScript. Now it’s time to see how to use the filter() in our JavaScript code.

The filter() is a function on the array that accepts another function as its argument which it will use to return new filtered version of the array.

Let’s take an array to experiment

var games = [
    { name: 'cricket', type: 'outdoor' },
    { name: 'football', type: 'outdoor' },
    { name: 'chess', type: 'indoor' },
    { name: 'carrom', type: 'indoor' }
];

It’s a pretty simple array, doesn’t it? We are going to use the same array in all the code throughout the post.

Now we are going to filter out the games from the array which are played in outdoor.

So, as always let me do this by using for loop.

var outdoorGames = [];
for (var i = 0; i < games.length; i++) {
    if (games[i].type == 'outdoor')
        outdoorGames.push(games[i])
}

console.log(outdoorGames);

Lets the write output in the console.

Output
[Object, Object]
    0: 
        Objectname: "cricket"
        type: "outdoor"
    1:
        Objectname: "football"
        type: "outdoor"

Yeah! We have achieved what we want in the output. We have extracted the outdoor game names from the game’s array.

Now, Let’s use the filter() in our code to get the similar output. Let’s rewrite the code.

We have the filter which accepts one argument which is a function. The filter will loop through each item in the array, so we don’t have to initialize index or iterate the loop as we did in the for loop.
And each item will be passed into callback function and it will return whether the condition ‘outdoor’ satisfies or not.

When we reduce the number of lines in the code, it doesn’t mean the code becomes faster unless it actually does.

var games = [
    { name: 'cricket', type: 'outdoor' },
    { name: 'football', type: 'outdoor' },
    { name: 'chess', type: 'indoor' },
    { name: 'carrom', type: 'indoor' }
];

function isOutdoor(game) {
    return game.type == 'outdoor';
}

var filteredOutdoor = games.filter(isOutdoor);

console.log(filteredOutdoor);
// output
[Object, Object]
    0: 
        Objectname: "cricket"
        type: "outdoor"
    1:
        Objectname: "football"
        type: "outdoor"

We get similar output when we use a filter().

Now in ES6, let’s simply more using arrow function

var filteredOutdoorArrow = games.filter(game => game.type == "outdoor");

console.log(filteredOutdoorArrow);

Now it’s up to us to decide which module we have to use in our code – the code using a pure function or using the loops.

Let’s explore more about functional programming in upcoming posts.

Happy coding!

map() – JavaScript Functional Programming

What is functional programming?

Functional programming is a programming paradigm, the process of building components using pure functions and avoiding shared state, mutable data and side-effects.

In simple, functional programming is doing our tasks with functions, avoiding side effects by using pure functions.

For example, Without iterating the list using user defined loops; we can iterate the list using the functions like map(), reduce(), and filter()

Let’s see about map() function in this post.

I have started exploring about functional programming in recent times. The topic looks very interesting and helping me to optimize my own codes. After using functional programming, my code looks pretty good and maintainable.

For example, If I need to iterate a list and extract some data previously I use some for loops to do the task like following:

var players = [
 { name: 'Dhoni', nickname: 'Super Cool Captain' },
 { name: 'Raina', nickname: 'Furious fielder' },
 { name: 'Ashwin', nickname: 'Spin Master' }
];

var namelistusingloop = [];

for (var i = 0; i < players.length; i++) {
 namelistusingloop.push(players[i].name);
}

Later I found that using map function, we can simplify our function even more.

map() will take the callback function as follows.

var namelistusingmap = players.map(function (player) {
 return player.name;
});

In the above part, the map() will iterate the list based on its length. We don’t have to initialize & iterate list as we did in the for loop.

Now the code looks simple and effective. All the short code doesn’t mean effective unless it reduces the development time & maintenance period.

We can even simplify the code with map() using arrow functions.

var namelistwitharrow = players.map((player) => player.name);

In short, arrow function is used to simplify our callback function. To know more about arrow functions click here to visit the earlier post in this space.

Now the code looks even cooler and smart

var namelistusingmap = players.map(function (player) {
 return player.name;
});

var namelistwitharrow = players.map((player) => player.name);

Lets put all code together to compare to take quick look,

var players = [
 { name: 'Dhoni', nickname: 'Super Cool Captain' },
 { name: 'Raina', nickname: 'Furious fielder' },
 { name: 'Ashwin', nickname: 'Spin Master' }
];

// using loops
var namelistusingloop = [];

for (var i = 0; i < players.length; i++) {  namelistusingloop.push(players[i].name); } // using map function var namelistusingmap = players.map(function (player) {  return player.name; }); // using map function and arrow function var namelistwitharrow = players.map((player) => player.name);

console.log(namelistusingloop);
console.log(namelistusingmap);
console.log(namelistwitharrow);


Output

["Dhoni", "Raina", "Ashwin"]
["Dhoni", "Raina", "Ashwin"]
["Dhoni", "Raina", "Ashwin"]

Now it’s up to us to decide which module we have to use in our code – the code using the pure function or using the loops.

Let’s explore more about functional programming in upcoming posts.

Happy coding!