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
});
You can simplify code as shown it below:
let selected_user=data.filter(function(user) {
return user.name==="prakash"
})
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")
Conclusion
Filter method returns a new array consisting only those
elements that satisfied the provided function.Filter method does not change original array.
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)
You could further simplify by removing the unnecessary parentheses:
Yeah we can do!..
Thank you for this post.
I have learned something thanks to you :)
Thanks for commenting.Keep learning!...
Did you ask for permission to use the image as a cover photo? You can clearly see flaviocopes.com on the bottom?
Thanks for informing me.I changed cover photo.
Thanks @lukeshiru for giving more suggestions !..