Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 20, 2021 05:09 am GMT

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

  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.


Original Link: https://dev.to/jyothiprakashk/javascript-filter-4i9a

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To