Mona Alfonso

Mona Alfonso

Web Developer and Educator with 5+ years of experience in tech.

Explainer

The .filter() method is used to create a new array with all elements that pass the test implemented by the provided function. It's particularly useful for selecting specific elements from an array based on certain criteria, without modifying the original array. This post breaks down the .filter() method step by step to help you better understand how it works.

Example #1: Using the Filter Method with an Array of Numbers

Let's use a simple example of filtering out even numbers from an array:

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

Now, let's break it down in pseudo-code:

Initialize:

  • numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • filter function starts
  • new empty array created to store results

First iteration:

  • currentValue = 1
  • Condition: 1 % 2 === 0 (false)
  • 1 is not added to the new array

Second iteration:

  • currentValue = 2
  • Condition: 2 % 2 === 0 (true)
  • 2 is added to the new array

Third iteration:

  • currentValue = 3
  • Condition: 3 % 2 === 0 (false)
  • 3 is not added to the new array

Fourth iteration:

  • currentValue = 4
  • Condition: 4 % 2 === 0 (true)
  • 4 is added to the new array

Fifth iteration:

  • currentValue = 5
  • Condition: 5 % 2 === 0 (false)
  • 5 is not added to the new array

Sixth iteration:

  • currentValue = 6
  • Condition: 6 % 2 === 0 (true)
  • 6 is added to the new array

Seventh iteration:

  • currentValue = 7
  • Condition: 7 % 2 === 0 (false)
  • 7 is not added to the new array

Eighth iteration:

  • currentValue = 8
  • Condition: 8 % 2 === 0 (true)
  • 8 is added to the new array

Ninth iteration:

  • currentValue = 9
  • Condition: 9 % 2 === 0 (false)
  • 9 is not added to the new array

Tenth iteration:

  • currentValue = 10
  • Condition: 10 % 2 === 0 (true)
  • 10 is added to the new array

End of array reached:

  • New array [2, 4, 6, 8, 10] is returned as the result of .filter()

Finally, our evenNumbers array contains [2, 4, 6, 8, 10].

The .filter() method creates a new array with all elements that pass the test implemented by the provided function. It doesn't change the original array, which makes it a pure function and useful in functional programming paradigms.

Example #2: Using the Filter Method with an Array of Objects

Here is another example, this time using an array of objects:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
  { name: 'David', age: 28 },
  { name: 'Eve', age: 22 }
];
 
const over30 = people.filter((person) => {
  return person.age > 30;
});
 
console.log(over30); // Output: [{ name: 'Charlie', age: 35 }]

Now, let's break this down step by step in pseudo-code:

Initialize:

  • people = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 }, { name: 'David', age: 28 }, { name: 'Eve', age: 22 }]
  • filter function starts
  • new empty array created to store results

First iteration:

  • currentValue = { name: 'Alice', age: 25 }
  • Condition: 25 > 30 (false)
  • Object is not added to the new array

Second iteration:

  • currentValue = { name: 'Bob', age: 30 }
  • Condition: 30 > 30 (false)
  • Object is not added to the new array

Third iteration:

  • currentValue = { name: 'Charlie', age: 35 }
  • Condition: 35 > 30 (true)
  • Object is added to the new array

Fourth iteration:

  • currentValue = { name: 'David', age: 28 }
  • Condition: 28 > 30 (false)
  • Object is not added to the new array

Fifth iteration:

  • currentValue = { name: 'Eve', age: 22 }
  • Condition: 22 > 30 (false)
  • Object is not added to the new array

End of array reached:

  • New array [{ name: 'Charlie', age: 35 }] is returned as the result of filter()

Finally, over30 now contains [{ name: 'Charlie', age: 35 }]

This example demonstrates how .filter() can be used to select specific elements from an array based on certain criteria. It's a versatile method that can be used for any kind of selection or filtering operation on an array.

Practice Problems

Here are 5 practice problems to help you learn how to use the .filter() function, arranged from easiest to more complex. The first problem includes a function stub to get you started.

  1. Filter Positive Numbers: Create a new array with only the positive numbers from the original array.
const numbers = [-3, 1, -4, 5, 9, -2, 6];
 
function filterPositive(arr) {
  return arr.filter((number) => {
    // Your code here
  });
}
 
console.log(filterPositive(numbers)); // Expected output: [1, 5, 9, 6]
  1. Filter Long Words: Given an array of words, create a new array containing only words longer than 5 characters.

  2. Filter Prime Numbers: Given an array of numbers, create a new array containing only prime numbers.

  3. Filter Unique Values: Given an array with duplicate values, create a new array with only unique values.

  4. Filter by Multiple Criteria: Given an array of objects representing products (with properties like name, price, and category), create a new array of products that meet multiple criteria (e.g., price range and specific category).

These problems will help you practice using .filter() in various scenarios, from simple selections to more complex filtering operations. Try to solve them on your own, and if you need hints or solutions, feel free to ask!