Introduction to Filter method in javascript

Introduction to Filter method in javascript

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

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 Array of Object?

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"}]

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment