Important notes about the filter method

The filter method is defined on Array.prototype, so we call it on any array, and it accepts a callback as its first argument.

In the above code we are passing just one argument to the function, that is the current number. But we can pass a total of three arguments to this function:

The current item in the array

The array index of the current item

The entire array you called map on

The return statement. We have to make sure that the return statement returns a boolean value. If we forget the return statement, the function will return undefined and filter will assume it as false and we will get an empty array. And if the return statement does not return a boolean value, JavaScript logic will be applied to figure out if it’s true or false, which always results in hidden bugs.

We can also use ES6(ES2015) ‘fat arrow’ :

JavaScript

1

2

let tenNumbers=[1,2,3,4,5,6,7,8,9,10];

let evenNumbers=tenNumbers.filter(num=>num%2===0);

And now a look at a more practical example, suppose we call an API that returns an array of objects. Something like this :

JavaScript

1

2

3

4

5

6

7

let userDetails=[

{'name':'User1','age':46},

{'name':'User2','age':36},

{'name':'User3','age':26},

{'name':'User4','age':16},

{'name':'User5','age':14}

];

Now, we decide that we just want to display users above the age of 18. Here is how we will achieve this:

JavaScript

1

2

3

4

5

6

7

8

let userDetails=[

{'name':'User1','age':46},

{'name':'User2','age':36},

{'name':'User3','age':26},

{'name':'User4','age':16},

{'name':'User5','age':14}

];

let adultUsers=userDetails.filter(user=>user.age>=18);

Note, in case you are using Angular, it would be a good idea to use a pipe to achieve this result.