In this tutorial, we will learn about how to use and when to use the Filter method in JavaScript.

What is the Filter method?

The Filter() method is Used to filter for elements in the original array that satisfy a certain condition

Basically, Filter() method returns a new array containing the array elements that passed a specified test condition and leaves the original array untouched.

For Example,

Suppose we have an array as follows:

let arr = [300, 450, -400, 1000, -65, -13, 70, 300];

Now, we want's to get only positve value from it, so we can do this using filter as follows:

let modifiedArr =  arr.filter(function(num){
  return num > 0;
});

console.log(modifiedArr);//[300, 450, 1000, 70, 300]

How to Filter an Array of Objects?

Now suppose we have an array of objects as follows:

let users = [
    {name: "sam", country: "us"},
    {name: "steve", country: "uk"},
    {name: "john", country: "uk"},
    {name: "phillip", country: "india"}
];

Here, we want's to get list of users who belongs to uk, then we can filter as follows:

let filteredData = users.filter(function(ele){
    return ele.country=='uk'
})

console.log(filteredData);
//[{"name":"steve","country":"uk"},{"name":"john","country":"uk"}]

Conclusion:

🙏 Thanks for reading.

Do let me know If you face any difficulties please feel free to comment below we love to help you.

If you have any feedback suggestions then please inform us by commenting.

Don’t forget to share this tutorial with your friends on Facebook and Twitter

Topics covered:

Found this article helpful?

TutsCoder tutorials are free and ad-light — supported by readers like you. Buy me a coffee (or two ☕☕) as a token of appreciation and help keep Angular & Node.js content coming!

One-time. No subscription. 100% optional. 🙏 Every coffee counts!

Leave a Comment

Your email will not be published. Spam-free zone. ✌️

Available for Projects

Need Help With Your
Angular or Node.js Project?

7+ years of MEAN Stack experience. I build scalable Angular 21 apps, Node.js APIs, and SaaS products — delivered on time, every time.

7+ Years MEAN Stack Angular 21 + Nx Expert 20+ Projects Delivered Remote / Freelance