Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Filtering Arrays with `filter()`

Hello! Welcome to your next lesson on modern JavaScript.

Introduction

In our last lesson, we mastered the map method, learning how to transform each item in an array into something new. We saw that map always returns a new array with the exact same number of items as the original.

Today, we'll explore a related and equally powerful array method: filter. This lesson directly addresses the learning outcome: Create new arrays by selecting data using the filter method.

While map is for transforming data, filter is for selecting data. As a designer, you constantly create interfaces that allow users to filter content—showing only unread messages, products within a certain price range, or tasks assigned to a specific person. The filter method is the JavaScript tool that powers these features. It lets you create a new array containing only the elements from an original array that meet your specific criteria.

In this lesson, we will cover:

  • The core concept of the filter method and how it works.
  • How to use filter with arrow functions to select elements based on a condition.
  • The most common use case: filtering arrays of objects based on their properties.

1. The Core Concept: Selecting with filter

The filter method creates a new array with all elements that pass a test implemented by a provided function. It iterates through an array and, for each element, it calls your callback function. This callback function must return a boolean value:

  • If the callback returns true, the element is included in the new array.
  • If the callback returns false, the element is excluded.

Crucially, like map, filter is immutable. It does not change the original array; it returns a brand new one.

Let's start with a video that demonstrates this core concept using a simple array of numbers.

JavaScript Array Filter

This video from Programming with Mosh provides a perfect introduction to filter. It starts with a clear, simple example and shows how to write the code using both a traditional function and a modern, concise arrow function.

Watch from the beginning to 02:06. Pay close attention to how the callback function's return value (a boolean) determines whether a number is included in the final filtered array.

As you saw, the logic is very declarative. Instead of telling the computer how to loop and add items to a new array, you simply declare the condition for an item to be kept.

Here's the basic structure using an arrow function, which you'll use most of the time:

const numbers = [-10, 0, 5, -2, 8];

// The callback function `n => n >= 0` returns true for non-negative numbers.
const positiveNumbers = numbers.filter(n => n >= 0);

console.log(positiveNumbers); // Output: [0, 5, 8]
console.log(numbers);         // Output: [-10, 0, 5, -2, 8] (The original is unchanged)

2. When and How to Use filter

To solidify your understanding, let's look at a quick article that defines filter and its use case.

The Beginner's Guide to forEach, map and filter in JavaScript

This article from Northcoders, 'The Beginner's Guide to forEach, map and filter in JavaScript', gives a very clear and concise explanation of what filter does and when you should use it.

Read the section titled '.filter()'. It starts right after the map() section. Focus on the core idea: the function you provide must return true or false to decide if an element should be included.

The key takeaway is in the name itself: use filter whenever you need to create a smaller, selected subset of an array based on some criteria.


3. Filtering Arrays of Objects

Filtering simple arrays of numbers or strings is useful, but the real power of filter shines when you work with arrays of objects. This is what you'll do constantly when building UIs. You might get a large list of data from an API and need to show only the items that match a user's selection.

Let's say you have a list of user profiles and want to find all the admin users. Or you have a list of products and want to show only the ones that are in stock. filter is the perfect tool for this.

The following video demonstrates this with a fun example using Star Wars characters.

JavaScript Array Filter Method Practice in 5 Minutes

This video from James Q Quick, 'JavaScript Array Filter Method Practice in 5 Minutes', walks through several practical examples of filtering an array of objects based on different property values.

Watch the following segments to see how to filter by different conditions: Filtering by a numeric property: Watch from 01:07 to 02:12 to see how he filters characters with a mass greater than 100. Filtering by another numeric property: Watch from 02:51 to 03:58 to see filtering by height less than 200. Filtering by a string property: Watch from 03:58 to 04:49 to see how he selects only the male characters.

The pattern is always the same:

  1. Call .filter() on your array of objects.
  2. In the callback, access the property you want to test (e.g., character.gender).
  3. Return the result of a comparison (e.g., character.gender === 'male').

Here is a text resource that reinforces this with a clear before-and-after code example.

How the JavaScript Filter Method Works – Explained with ...

This freeCodeCamp article, 'How the JavaScript Filter Method Works', provides excellent side-by-side comparisons of solving problems with a traditional for loop versus the filter method. This really highlights the clarity and conciseness filter provides.

Read the section 'Filtering Objects Based on Property Values'. Compare the 'Without Filter' and 'With Filter' code blocks to see how much cleaner the modern approach is.


4. Practice Exercise

Now it's your turn. Imagine you're working on a design system and have a list of components. You need to build a UI that allows designers to filter this list.

Your Goal:
You are given an array of components. Use the filter method to create two new arrays:

  1. interactiveComponents: An array containing only the components where the isInteractive property is true.
  2. largeComponents: An array containing only the components where the size property is 'large'.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter Practice</title>
    <style>
        body { font-family: sans-serif; }
        pre { background-color: #f4f4f4; padding: 1em; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>Component Library</h1>

    <script>
        const components = [
            { id: 'btn-01', name: 'Primary Button', type: 'button', size: 'medium', isInteractive: true },
            { id: 'crd-01', name: 'Info Card', type: 'card', size: 'large', isInteractive: false },
            { id: 'inp-01', name: 'Text Input', type: 'input', size: 'medium', isInteractive: true },
            { id: 'btn-02', name: 'Large Destructive Button', type: 'button', size: 'large', isInteractive: true },
            { id: 'hdr-01', name: 'Page Header', type: 'header', size: 'large', isInteractive: false }
        ];

        let interactiveComponents;
        let largeComponents;

        // --- YOUR CODE HERE ---
        
        // 1. Filter `components` to get only the ones where `isInteractive` is true.
        // Assign the result to `interactiveComponents`.
        
        
        // 2. Filter `components` to get only the ones where `size` is 'large'.
        // Assign the result to `largeComponents`.


        // --- END OF YOUR CODE ---


        // This code will display your results on the page
        document.body.innerHTML += '<h2>Interactive Components</h2>';
        document.body.innerHTML += `<pre>${JSON.stringify(interactiveComponents, null, 2)}</pre>`;
        
        document.body.innerHTML += '<h2>Large Components</h2>';
        document.body.innerHTML += `<pre>${JSON.stringify(largeComponents, null, 2)}</pre>`;
    </script>
</body>
</html>
Click here for the solution
// Solution for interactive components
interactiveComponents = components.filter(component => component.isInteractive === true);

// A shorter way to write the same thing, since component.isInteractive is already a boolean:
interactiveComponents = components.filter(component => component.isInteractive);

// Solution for large components
largeComponents = components.filter(component => component.size === 'large');

Conclusion

Great job! You've now added filter to your JavaScript toolkit. You've seen how it works, how it differs from map, and how to use it to select data—especially from complex arrays of objects. This is a skill you will use daily as a front-end developer.

Key Takeaways:

  • Selection, Not Transformation: filter creates a new, smaller array by selecting elements that meet a condition. The elements themselves are not changed.
  • Boolean Return: The callback function you provide to filter must return true (to keep the element) or false (to discard it).
  • Immutability: filter does not modify the original array.
  • UI Foundation: Filtering is a fundamental pattern for building interactive user interfaces that respond to user input.

In our next lesson, we'll take a step back and look at how to keep our growing codebases organized. We'll learn about ES6 Modules, which allow us to split our JavaScript code across multiple files using import and export statements. This is essential for building larger, maintainable applications.

Can't find a good explanation? Sign up and we'll make it for you

Sign up