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!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s