JavaScript Filter

Definition
Filter Tips
Conclusion

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 li…


This content originally appeared on DEV Community and was authored by k.Jyothi Prakash Reddy

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.


This content originally appeared on DEV Community and was authored by k.Jyothi Prakash Reddy


Print Share Comment Cite Upload Translate Updates
APA

k.Jyothi Prakash Reddy | Sciencx (2021-11-20T05:09:33+00:00) JavaScript Filter. Retrieved from https://www.scien.cx/2021/11/20/javascript-filter/

MLA
" » JavaScript Filter." k.Jyothi Prakash Reddy | Sciencx - Saturday November 20, 2021, https://www.scien.cx/2021/11/20/javascript-filter/
HARVARD
k.Jyothi Prakash Reddy | Sciencx Saturday November 20, 2021 » JavaScript Filter., viewed ,<https://www.scien.cx/2021/11/20/javascript-filter/>
VANCOUVER
k.Jyothi Prakash Reddy | Sciencx - » JavaScript Filter. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/20/javascript-filter/
CHICAGO
" » JavaScript Filter." k.Jyothi Prakash Reddy | Sciencx - Accessed . https://www.scien.cx/2021/11/20/javascript-filter/
IEEE
" » JavaScript Filter." k.Jyothi Prakash Reddy | Sciencx [Online]. Available: https://www.scien.cx/2021/11/20/javascript-filter/. [Accessed: ]
rf:citation
» JavaScript Filter | k.Jyothi Prakash Reddy | Sciencx | https://www.scien.cx/2021/11/20/javascript-filter/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.