DEV Community

Cover image for JavaScript Filter
k.Jyothi Prakash Reddy
k.Jyothi Prakash Reddy

Posted on • Updated on

JavaScript Filter

Definition

The filter() method returns new array with all the elements that pass the test implemented by provided function.

Filter Tips

Check below code for filter.

If you have array like this.

const data=[
  {name:"prakash",age:20},
  {name:"bhanu",age:21},
  {name:"mohan",age:40}
];

// Then instead of writing code like this 
const select_user=data.filter(function(user){
    if (user.name==="prakash"){
       return true
    }
    return false
});
Enter fullscreen mode Exit fullscreen mode

You can simplify code as shown it below:


let selected_user=data.filter(function(user) {
    return user.name==="prakash"
})

Enter fullscreen mode Exit fullscreen mode

The above code will return true,if the condition is satisfied otherwise it will return false

We can simplify above code much more simple and understandable using ES6 syntax.


let selected_user=data.filter((user)=> user.name==="prakash")

Enter fullscreen mode Exit fullscreen mode

Conclusion

  1. Filter method returns a new array consisting only those
    elements that satisfied the provided function.

  2. Filter method does not change original array.

  3. Filter method does not execute function for empty elements.

I hope You will learn something from this post.If there are more usecases, please mention in below comment section.

Thanks.

Top comments (7)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You could further simplify by removing the unnecessary parentheses:

let selected_user=data.filter(user => user.name==="prakash")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jyothiprakashk profile image
k.Jyothi Prakash Reddy

Yeah we can do!..

Collapse
 
vendkura profile image
Giovanni

Thank you for this post.
I have learned something thanks to you :)

Collapse
 
jyothiprakashk profile image
k.Jyothi Prakash Reddy

Thanks for commenting.Keep learning!...

Collapse
 
robole profile image
Rob OLeary

Did you ask for permission to use the image as a cover photo? You can clearly see flaviocopes.com on the bottom?

Collapse
 
jyothiprakashk profile image
k.Jyothi Prakash Reddy

Thanks for informing me.I changed cover photo.

Collapse
 
jyothiprakashk profile image
k.Jyothi Prakash Reddy

Thanks @lukeshiru for giving more suggestions !..