Array.filter() Method

mrizwanashiq

Muhammad Rizwan Ashiq

Posted on June 15, 2023

Array.filter() Method

What is Filter Method?

The filter() method is used to filter the elements of an array based on a condition. It returns a new array containing all elements that pass the test implemented by the provided function. The filter() method does not change the original array.

Syntax

Here's the syntax for using filter():

const filteredArray = arr.filter((element, index, array) => {
    // Return true to keep the element, false otherwise
});
Enter fullscreen mode Exit fullscreen mode

The callback function is called for each element in the array and takes the following arguments:

  • element: the current element being processed in the array
  • index (optional): the index of the current element
  • array (optional): the array that filter() is being applied to

The filter() method calls the callback function once for each element in the array, in order, and constructs a new array from the elements for which the callback function returns true. The length of the new array will be equal to or less than the length of the original array, depending on the elements that pass the test.

Here's an example of how to use filter() to get all the even numbers from an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter(function (number) {
    if (number % 2 === 0) {
        return true;
    } else {
        return false;
    }
});

console.log(evenNumbers); 
// prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

In the example above, the callback function is an anonymous function that takes a single argument, number, and returns true if number is even, and false otherwise. The filter() method calls this function for each element in the numbers array and creates a new array with the elements that return true.

You can also use an arrow function as the callback function, like this:

let evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); 
// prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

The filter() method is useful for creating a new array from a subset of the elements in an array, based on a certain condition.

Examples

Here are a few more examples of how you can use filter():

Getting the products with a price greater than 10

const products = [
    { id: 1, name: "Product 1", price: 10 },
    { id: 2, name: "Product 2", price: 15 },
    { id: 3, name: "Product 3", price: 20 },
];

const expensiveProducts = products.filter((product) => product.price > 10);

console.log(expensiveProducts); 
// prints [{ id: 2, name: 'Product 2', price: 15 }, { id: 3, name: 'Product 3', price: 20 }]
Enter fullscreen mode Exit fullscreen mode

Getting the users which live in a particular city

const users = [
    { id: 1, name: "John", city: "Islamabad" },
    { id: 2, name: "Jane", city: "Lahore" },
    { id: 3, name: "Jack", city: "Karachi" },
    { id: 4, name: "Jill", city: "Rahim Yar Khan" },
    { id: 5, name: "Joe", city: "Islamabad" },
    { id: 6, name: "Jen", city: "Lahore" },
];

const usersInIslamabad = users.filter((user) => user.city === "Islamabad");
console.log(usersInIslamabad);
// prints [{ id: 1, name: 'John', city: 'Islamabad' }, { id: 5, name: 'Joe', city: 'Islamabad' }]

const usersInLahore = users.filter((user) => user.city === "Lahore");
console.log(usersInLahore);
// prints [{ id: 2, name: 'Jane', city: 'Lahore' }, { id: 6, name: 'Jen', city: 'Lahore' }]

const usersInKarachiOrRahimYarKhan = users.filter(
    (user) => user.city === "Karachi" || user.city === "Rahim Yar Khan"
);
console.log(usersInKarachiOrRahimYarKhan);
// prints [{ id: 3, name: 'Jack', city: 'Karachi' }, { id: 4, name: 'Jill', city: 'Rahim Yar Khan' }]

const usersInKarachiAndRahimYarKhan = users.filter(
    (user) => user.city === "Karachi" && user.city === "Rahim Yar Khan"
);
console.log(usersInKarachiAndRahimYarKhan);
// prints []
Enter fullscreen mode Exit fullscreen mode

Getting the users which are not admins

const users = [
    { id: 1, name: "John", isAdmin: true },
    { id: 2, name: "Jane", isAdmin: false },
    { id: 3, name: "Jack", isAdmin: false },
    { id: 4, name: "Jill", isAdmin: true },
    { id: 5, name: "Joe", isAdmin: false },
    { id: 6, name: "Jen", isAdmin: true },
];

const nonAdminUsers = users.filter((user) => !user.isAdmin);
console.log(nonAdminUsers);
// prints [{ id: 2, name: 'Jane', isAdmin: false }, { id: 3, name: 'Jack', isAdmin: false }, { id: 5, name: 'Joe', isAdmin: false }]
Enter fullscreen mode Exit fullscreen mode

Getting the users which are not admins and live in a particular city

const users = [
    { id: 1, name: "John", city: "Islamabad", isAdmin: true },
    { id: 2, name: "Jane", city: "Lahore", isAdmin: false },
    { id: 3, name: "Jack", city: "Karachi", isAdmin: false },
    { id: 4, name: "Jill", city: "Rahim Yar Khan", isAdmin: true },
    { id: 5, name: "Joe", city: "Islamabad", isAdmin: false },
    { id: 6, name: "Jen", city: "Lahore", isAdmin: true },
];

const nonAdminUsersInIslamabad = users.filter(
    (user) => !user.isAdmin && user.city === "Islamabad"
);
console.log(nonAdminUsersInIslamabad);
// prints [{ id: 5, name: 'Joe', city: 'Islamabad', isAdmin: false }]
Enter fullscreen mode Exit fullscreen mode

Get the list of products which belong to a particular category

const products = [
    { id: 1, name: "Phone", category: "Electronics" },
    { id: 2, name: "Laptop", category: "Electronics" },
    { id: 3, name: "Shirt", category: "Clothing" },
    { id: 4, name: "Pants", category: "Clothing" },
    { id: 5, name: "Socks", category: "Clothing" },
    { id: 6, name: "Watch", category: "Accessories" },
    { id: 7, name: "Tie", category: "Accessories" },
    { id: 8, name: "Belt", category: "Accessories" },
];

const electronicsProducts = products.filter(
    (product) => product.category === "Electronics"
);
console.log(electronicsProducts);

const clothingProducts = products.filter(
    (product) => product.category === "Clothing"
);
console.log(clothingProducts);

const accessoriesProducts = products.filter(
    (product) => product.category === "Accessories"
);
console.log(accessoriesProducts);
Enter fullscreen mode Exit fullscreen mode

filter() vs map()

The filter() method is similar to the map() method. Both methods create a new array from an existing array. The difference is that the filter() method returns a new array that contains only the elements that pass a certain condition, while the map() method returns a new array with the results of calling a callback function on every element in the original array. Here's an example:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter((number) => number % 2 === 0);

const evenNumbersSquared = evenNumbers.map((number) => number * number);

console.log(evenNumbersSquared); 
// prints [4, 16, 36, 64, 100]
Enter fullscreen mode Exit fullscreen mode

In the example above, we first use the filter() method to create a new array with only the even numbers. Then we use the map() method to create a new array with the squares of the even numbers.

filter() vs forEach()

The filter() method is similar to the forEach() method. Both methods iterate over an array and call a callback function on each element in the array. The difference is that the filter() method returns a new array that contains only the elements that pass a certain condition, while the forEach() method does not return anything. Here's an example:

In forEach():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = [];

numbers.forEach((number) => {
    if (number % 2 === 0) {
        evenNumbers.push(number);
    }
});

console.log(evenNumbers); 
// prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

In the example above, we first create an empty array called evenNumbers. Then we use the forEach() method to iterate over the numbers array and push the even numbers into the evenNumbers array.

In filter():

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers); 
// prints [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

In the example above, we use the filter() method to create a new array with only the even numbers.

When to use filter()

The filter() method is useful when you want to create a new array that contains only the elements that pass a certain condition. It's also useful when you want to remove elements from an array that don't pass a certain condition. Here are some examples:

Like Getting the users which are not admins

const users = [
    { id: 1, name: "John", isAdmin: true },
    { id: 2, name: "Jane", isAdmin: false },
    { id: 3, name: "Jack", isAdmin: false },
    { id: 4, name: "Jill", isAdmin: true },
    { id: 5, name: "Joe", isAdmin: false },
    { id: 6, name: "Jen", isAdmin: true },
];

const nonAdminUsers = users.filter((user) => !user.isAdmin);

console.log(nonAdminUsers);

// prints [{ id: 2, name: 'Jane', isAdmin: false }, { id: 3, name: 'Jack', isAdmin: false }, { id: 5, name: 'Joe', isAdmin: false }]
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we learned about the filter() method. We learned how to use the filter() method to create a new array with only the elements that pass a certain condition.

We also learned about the filter() method's similarities and differences with the map() and forEach() methods.

💖 💪 🙅 🚩
mrizwanashiq
Muhammad Rizwan Ashiq

Posted on June 15, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related