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!

C# 7.0 – Pattern Matching in Switch

C# 7.0 adds lots of new features to bring code simplification and performance. Pattern matching is one of the interesting features of C# 7.0.  Pattern Matching simplifies code that is conditional on the shape of data.

Pattern matching means we can switch based on the type of data to execute one or more statements.

For example, In previous times if we want to match more than one case in switch we used to do like the following

case 11:
case 12:
case 13:
    Console.Write("greater 10");
    break;

Using C# 7.0 pattern matching, we can set the range of input values in the switch cases using when. We can switch based on any type, can use pattern matching case clauses.

Let’s see an example of pattern matching,

switch (experience)
{
     case var exp when (experience > 0 & experience < 4):
         Console.Write("Junior stage with {0} years of experience level", exp);
         break;

      case var exp when (experience > 10):
         Console.Write("Super senior stage with {0} years of experience level", exp);
         break;

     case var exp when (new List<int>() { 4, 5, 6, 7 }).Contains(experience):
         Console.Write("Mid level stage with {0} years of experience level", exp);
         break;

     default:
         Console.Write("code hits the default case");
         break;
}

In the above code, the first case checks the experience greater than 0 and less than 4 using pattern matching. we can check more than condition using & which is similar to the way we use in if/for loops.

In the second case, we are matching only one conditional case in switch clause.

In the third case, we are checking whether the experience value is available in the list of int values we have. At final the default case works as always, and get executes at last if no other case clauses get hits.

In this pattern matching switch cases, the order of clauses is determining which pattern needs to be validated first.

The exp variable will have the value of experience variable on the successful pass of pattern matching.

I have used VS Code for executing this code and committed the source in this repo. Have a look 🙂

Happy coding 🙂