An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
November 20, 2021 05:09 am GMT
Original Link: https://dev.to/jyothiprakashk/javascript-filter-4i9a
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});
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.
Original Link: https://dev.to/jyothiprakashk/javascript-filter-4i9a
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To