What is the filter method, and how does it work?

The filter method is used to create a new array with elements that pass a specified test, making it useful for selectively extracting items based on criteria.

In this example, we are using the filter method, to create a new array of only even numbers:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
 
console.log(evenNumbers); // [2, 4, 6, 8, 10]

In this example, the filter method applies a callback function to each element of the numbers array. The callback checks whether each number is even using the modulo operator (%).

If the number is even, the function returns true, and that number is included in the new array. If it’s odd, the function returns false, and that number is excluded.

Just like the map method, the callback function for the filter method accepts the same three arguments: the current element being processed, the index, and the array.

It’s important to note that if no elements pass the test, the filter method returns an empty array.

const numbers = [2, 4, 6, 8].filter((num) => num > 10);
 
console.log(numbers); // []

filter is incredibly versatile and can be used in many scenarios. You can use it to remove null or undefined values from an array, to filter objects based on their properties, or to implement search functionality.

Here’s an example of using the filter method to return an array of objects for individuals younger than 30 years old.

const developers = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 },
  { name: "David", age: 25 }
];
 
const youngPeople = developers.filter((person) => person.age < 30);
console.log(youngPeople);
 
// [{ name: "Alice", age: 25 }, { name: "David", age: 25 }]

Throughout the rest of this curriculum, you will be using the map and filter methods very frequently. So, building familiarity with them will not only streamline your coding process but also help you write cleaner and more efficient code.