My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
JavaScript Filter Method Explained

JavaScript Filter Method Explained

Kaarthik Sekar's photo
Kaarthik Sekar
·Jul 16, 2021·

2 min read

Array Filter Method:

This method just return a new array with items based on the conditions included in callback function. This callback function accepts one parameter ie: each item in array and returns boolean based on the condition. Here is a simple data ,

const friends = [
    {
        name: 'Peter Parker',
        gender: 'male',
        age: 34,
    },
    {
        name: 'Kyle Simpson',
        gender: 'male',
        age: 32,
    },
    {
        name: 'Sara Williams',
        gender: 'female',
        age: 27,
    },
    {
        name: 'Annie Matthew ',
        gender: 'female',
        age: 35,
    },
    {
        name: 'Robert ',
        gender: 'male',
        age: 25,
    },
];

Now let's say we want to filter this array based on the condition age < 35

So, the entire filter would look like this.

const lessThanThirtyFive = friends.filter((friends)=>{
    return friends.age < 35;
});
console.log(lessThanThirtyFive);

Output:

This will return a new array based on the condition friends.age > 35

/*
[
  { name: 'Peter Parker', gender: 'male', age: 34 },
  { name: 'Kyle Simpson', gender: 'male', age: 32 },
  { name: 'Sara Williams', gender: 'female', age: 27 },
  { name: 'Robert ', gender: 'male', age: 25 }
]
*/

Conclusion:

You can use the filter() array method to create a new array from the contents of an existing array. The clue is in the name with the filter() method. filter() filters out elements from an existing array.

What is your thought about filter method ? Comment it below 👨🏻‍💻