Hello! Welcome to the next lesson in our journey through JavaScript's powerful array methods.
In our last lesson, we mastered the map() method. We saw how it's used to create a new array by applying a transformation to every single element of an original array. This is perfect when you need to change each item into something new.
But what if you don't want to transform every item? What if you want to select only a subset of items that meet a specific condition? For example, finding all users over a certain age, or all products currently in stock. This is where the filter() method shines.
Today, you will learn how to create new arrays containing only elements that pass a test using the filter() method. This is a fundamental skill for cleaning, searching, and managing data, and it works hand-in-hand with map() to perform powerful data manipulations.
The Core Idea: Selection, Not Transformation
The filter() method does exactly what its name suggests: it acts like a sieve, letting only the elements you want pass through into a new array.
Here's the process:
filter()iterates over each element in an array.- For each element, it executes a "test" function you provide (a callback).
- This callback function must return a boolean value:
trueorfalse. - If the callback returns
true, the element is kept and added to the new array. - If the callback returns
false, the element is discarded.
Just like map(), filter() is immutable—it does not change the original array; it returns a brand new one.
Since you prefer visual explanations, this image perfectly illustrates the concept:

How to Use the filter() Method
The syntax for filter() is straightforward and should feel familiar after learning map(). You call it on an array and pass it a callback function that defines your filtering logic.
Let's watch a short segment of a video that demonstrates this with some simple examples.
map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
The video 'map, filter & reduce' by Akshay Saini gives a clear introduction to filter() and its purpose.
Watch from 06:44 to 11:20. Pay attention to how the callback function's logic changes to filter for different conditions (odd numbers, even numbers, numbers greater than 4). Also, notice the different ways the function can be written: as a separate named function, an anonymous function, and finally as a concise arrow function.
As the video showed, you can write the filtering logic in several ways. For a simple array of numbers, here’s how you would filter for all numbers greater than 10 using a modern arrow function:
const numbers = [5, 20, 8, 15, 30, 3];
const numbersGreaterThan10 = numbers.filter(number => number > 10);
console.log(numbersGreaterThan10); // Output: [20, 15, 30]
console.log(numbers); // Output: [5, 20, 8, 15, 30, 3] (Original is unchanged)
The expression number > 10 evaluates to either true or false. filter() uses this result to decide whether to keep the number.
Under the Hood: How filter() Really Works
You've mentioned you enjoy understanding the deep theory behind how things work. So, let's demystify filter(). At its core, it's a powerful abstraction over a simple for loop and an if statement.
Unlock the power of array.filter() with a deep dive into its ...
The article 'Unlock the power of array.filter()' on dev.to provides a great explanation and a simplified implementation that shows what's happening internally.
Read the section titled 'How Array.filter() works under the hood'. It explains the process and shows a custom filter function. You can see it's just a loop that checks a condition and pushes matching items to a new array.
Seeing this implementation makes it clear that filter() isn't magic. It's just a clean, declarative way to express a very common programming pattern: creating an empty array, looping through another array, checking a condition, and conditionally pushing elements.
Practical Use Cases for filter()
Filtering simple numbers is a good start, but the real power of filter() comes when you work with more complex data, like the arrays of objects you'll often get from an API when building a Next.js application.
How to use the array filter() method in JavaScript
The LogRocket blog post 'How to use the array filter() method in JavaScript' covers several excellent real-world scenarios.
Read the section 'Practical use cases of the array filter() method'. Focus on the examples for 'Filtering objects by specific properties' and 'Searching in an array'. These are tasks you will perform constantly in web development.
Here are some key takeaways from those use cases:
-
Filtering Objects: You can easily filter an array of objects based on one of their properties. This is extremely useful for features like showing only "available" products or "active" users.
const products = [ { name: 'Laptop', inStock: true }, { name: 'Mouse', inStock: false }, { name: 'Keyboard', inStock: true } ]; const availableProducts = products.filter(product => product.inStock); // The test is `product.inStock`, which is already true or false! console.log(availableProducts); // Output: [{ name: 'Laptop', inStock: true }, { name: 'Keyboard', inStock: true }] -
Building a Search Feature:
filter()is the perfect tool for implementing client-side search. You can check if a string propertyincludes()a search term.const users = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }]; const searchQuery = 'b'; const searchResults = users.filter(user => user.name.toLowerCase().includes(searchQuery.toLowerCase()) ); console.log(searchResults); // Output: [{ name: 'Bob' }]
Test your understanding!
You have an array of book objects. Use the filter() method to create a new array that contains only the books written by 'J.K. Rowling'.
const books = [
{ title: 'The Hobbit', author: 'J.R.R. Tolkien' },
{ title: 'Harry Potter and the Sorcerer\'s Stone', author: 'J.K. Rowling' },
{ title: 'A Game of Thrones', author: 'George R.R. Martin' },
{ title: 'Harry Potter and the Chamber of Secrets', author: 'J.K. Rowling' }
];
// Your code here...
// const rowlingBooks = ?
What would the code be, and what would the rowlingBooks array contain?
Show answer
const rowlingBooks = books.filter(book => book.author === 'J.K. Rowling');
console.log(rowlingBooks);
Output:
[
{ title: 'Harry Potter and the Sorcerer\'s Stone', author: 'J.K. Rowling' },
{ title: 'Harry Potter and the Chamber of Secrets', author: 'J.K. Rowling' }
]
Explanation: The filter() method iterates over each book object. The arrow function book => book.author === 'J.K. Rowling' returns true only for the objects where the author property is exactly 'J.K. Rowling'. These two objects are then collected into the new rowlingBooks array.
Chaining filter() and map()
This is where your skills start to combine into something truly powerful. You can "chain" array methods together, passing the result of one method directly to the next. A very common pattern is to first filter an array to get the items you want, and then map over that smaller array to transform it into the shape you need.
Let's solve a practical problem: Get the first names of all users whose age is less than 30.
This requires two steps:
- Filter the
usersarray to get only the objects for users under 30. - Map over the resulting filtered array to extract just the
firstNamefrom each object.
This video demonstrates exactly how to chain these methods to solve this problem.
map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
Let's return to Akshay Saini's video. This final clip shows the power of chaining filter() and map() to solve a multi-step data problem.
Watch from 32:06 to 35:29. Follow along as he first filters the user list by age and then immediately chains .map() to the result to get the desired output. This is a crucial pattern for real-world application development.
Here is the code from the video, a beautiful example of declarative programming:
const users = [
{ firstName: "akshay", lastName: "saini", age: 26 },
{ firstName: "donald", lastName: "trump", age: 75 },
{ firstName: "elon", lastName: "musk", age: 50 },
{ firstName: "deepika", lastName: "padukone", age: 26 },
];
const output = users
.filter(user => user.age < 30) // Returns an array with akshay and deepika
.map(user => user.firstName); // Maps over that new array
console.log(output); // Output: ["akshay", "deepika"]
This code is clean, readable, and clearly expresses its intent without needing manual loops or temporary variables.
Conclusion
You've now learned how to select specific elements from an array using filter(). This, combined with map(), gives you a robust toolkit for most of the data manipulation tasks you'll encounter.
Key Takeaways:
filter()creates a new array containing only elements that pass a test.- The original array remains unchanged (immutability).
- The callback function you provide must return
true(to keep the element) orfalse(to discard it). filter()is essential for tasks like searching, cleaning data, and selecting items based on their properties.- You can chain
filter()withmap()(and other methods) to perform sophisticated, multi-step transformations on your data.
Next Up
You know how to perform an action for each element (forEach), transform every element (map), and now, select a subset of elements (filter). What's missing?
In our next lesson, we will explore the reduce() method. It's used to take an entire array and "reduce" it down to a single value, like calculating the sum of all numbers, finding the total price of items in a shopping cart, or even grouping elements into an object. This will complete the powerful trio of map, filter, and reduce.