DEV Community

Rajat Gupta
Rajat Gupta

Posted on

filter() method in JavaScript

Definition by MDN: The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Let's see some examples:

Example 1: Given an array of numbers, filter out all even numbers from the array?

const numbersArray = [1, 5, 22, 40, 3, 19, 6]

//Using arrow function
const newArray = numbersArray.filter(item => item % 2 === 0)
console.log(newArray)

Result: [22, 40, 6]



//Using normal function
function oddNumber(num){
    if(num % 2 === 0){
        return true
    }
}

const newArray = numbersArray.filter(oddNumber)
console.log(newArray)

Result: [22, 40, 6]
Enter fullscreen mode Exit fullscreen mode

As you saw above the filter method does justice to its name and is used to filter values of an array and returns a new array with those filtered values.

Note: It does not mutate the original array.

Here is what happens: Each element of the original array is passed through a function. The function will return either true or false. The element for which the function returns true will be appended to the new array and the element for which the function returns false will be discarded.

Note that the function will not return any other value other than true or false and if we try to return any other value it will be interpreted as either true or false. for example, 0 is false and any other value is true.

Let's see the below example:

Example 2:

const numbersArray = [1, 5, 22, 40, 3, 19, 6]
//Using normal function
function oddNumber(num){
    if(num % 2 === 0){
        return 0                         //0 is false
    }
}

const newArray = numbersArray.filter(oddNumber)
console.log(newArray)

Result: []
Enter fullscreen mode Exit fullscreen mode

Let's see another example.

Example 3: Given an array of numbers filter out all values greater than 6?

const numbersArray = [1, 5, 22, 40, 3, 19, 6]

//Using arrow function
const newArray = numbersArray.filter(item => item > 6)
console.log(newArray)

Result: [22, 40, 19]
Enter fullscreen mode Exit fullscreen mode

Let's see another example:

Example 4: given an array of strings, return an array of strings having vowels?

const stringArray = ["apple", "gpc", "banana", "dcrm", "mango", 'grapes', "sptj", 'guava', 'pineapple', 'strawberry']
const vowels = ['a', 'e', 'i', 'o', 'u']

//using arrow function
const newArray = stringArray.filter(item => { for(let i=0; i<5; i++){
    if(item.includes(vowels[i])){
        return true
    }}})
console.log(newArray)

Result: ['apple', 'banana', 'mango', 'grapes', 'guava', 'pineapple', 'strawberry']


//Using normal function
function vowelFilter(item){
    for(let i=0; i<5; i++){
        if(item.includes(vowels[i])){
            return true
        }
        else{
            return false
        }

const newArray = stringArray.filter(vowelFilter)

result: ['apple', 'banana', 'mango', 'grapes', 'guava', 'pineapple', 'strawberry']
Enter fullscreen mode Exit fullscreen mode

Let's see one last example:

Example 5: Given the below array:

const details = [{'firstName': 'Rajat', 'lastName': 'Gupta', 'age': 28},
{'firstName': 'Barack', 'lastName': 'Obama', 'age': 50},
{'firstName': 'Elon', 'lastName': 'Musk', 'age': 45},
{'firstName': 'Joe', 'lastName': 'Rogan', 'age': 36},
{'firstName': 'Abdul', 'lastName': 'Kalam', 'age': 64}]
Enter fullscreen mode Exit fullscreen mode

Can you filter out the firstName of the persons having an age of more than 46? (I recommend you to first try this out on your own. Here we'll use both map and filter, if you wanna know about map, read my blog here).

console.log(details.filter(item => item['age'] > 46).map(item => item['firstName']))
Result: ['Barack', 'Abdul']
Enter fullscreen mode Exit fullscreen mode

If you wanna know the long answer or the explanation of the above solution, tell me in the comment section and I'll be happy to write the same.

That's all folks.

I write one article every day related to web development (yes, every single f*cking day). Follow me here if you are learning the same..

If you love the article follow me on Twitter: @therajatg

If you are the Linkedin type, let's connect: https://www.linkedin.com/in/therajatg/

Have an awesome day ahead 😀!

Top comments (0)