How to Use the Filter Method in JavaScript
Keeping only the array items you need with filter, plus exercises.
There are times when you only need some of the items in an array, like the
products that are in stock or the users that are active. Instead of writing a
loop and pushing items into a new array, you can use the filter method.
The filter() method creates a new array with every item that passes the test
in your callback function.
How filter Works
filter calls your callback once for every item in the array. If the callback
returns a truthy value the item is kept, and if it returns a falsy value the
item is left out:
const result = arr.filter((element, index, array) => {// return true to keep the element, false to remove it})
The callback gets three arguments:
elementis the current itemindexis the position of the current itemarrayis the original arrayfilterwas called on
Most of the time you only need the first one.
Filtering Numbers
Here's a basic example that keeps only the even numbers:
const numbers = [1, 2, 3, 4, 5, 6]const evens = numbers.filter((number) => number % 2 === 0)console.log(evens) // [2, 4, 6]
For each number, number % 2 === 0 is either true or false, so only the
even numbers end up in evens.
Filtering an Array of Objects
This is where filter really comes in handy. Say you have a list of users and
only want the active ones:
const users = [{ name: "Jim", active: true },{ name: "Dwight", active: false },{ name: "Pam", active: true },]const activeUsers = users.filter((user) => user.active)// [{ name: "Jim", active: true }, { name: "Pam", active: true }]
It works just as well for a simple search:
const search = "pa"const results = users.filter((user) =>user.name.toLowerCase().includes(search))// [{ name: "Pam", active: true }]
Removing Falsy Values
Passing Boolean as the callback removes every falsy value from an array:
const values = ["hello", "", null, 42, undefined, false, "world"]const cleaned = values.filter(Boolean)console.log(cleaned) // ["hello", 42, "world"]
Boolean is a function that turns any value into true or false, so
filter(Boolean) is a short way of writing filter((value) => Boolean(value)).
Keep in mind 0 is falsy too, so it gets removed along with null and empty
strings.
Removing Duplicates
The index and array arguments let you remove duplicates. indexOf returns
the first index of a value, so an item is only kept if it's the first one of
its kind:
const tags = ["js", "react", "js", "css", "react"]const unique = tags.filter((tag, index, array) => array.indexOf(tag) === index)console.log(unique) // ["js", "react", "css"]
The second "js" is at index 2, but indexOf("js") returns 0, so it gets
filtered out. For arrays of strings or numbers, [...new Set(tags)] does the
same thing in less code.
Chaining filter with map
Since filter returns an array, you can chain other array methods right after
it. A common combo is filtering items and then pulling out a value with map:
const products = [{ name: "Keyboard", price: 80, inStock: true },{ name: "Mouse", price: 40, inStock: false },{ name: "Monitor", price: 300, inStock: true },]const inStockNames = products.filter((product) => product.inStock).map((product) => product.name)console.log(inStockNames) // ["Keyboard", "Monitor"]
filter Returns a New Array
filter never changes the original array. It always returns a new one, even
if every item passes or none of them do (in that case you get an empty array):
const numbers = [1, 2, 3]const bigNumbers = numbers.filter((number) => number > 10)console.log(bigNumbers) // []console.log(numbers) // [1, 2, 3]
Note: The new array is a shallow copy. If your array has objects in it, the filtered array points to the same objects, so changing one changes it in both places.
If you need fully separate objects, copy each one as you go, for example with
.map((user) => ({ ...user })) after the filter. And if you only need the
first match, find returns a single item instead of an array.
Practice Exercises
The best way to get comfortable with filter is to use it on a few small
problems. Try each one yourself before looking at the solution.
Exercise 1: Search by substring
Write a search function that returns the products whose name includes the
search term. It should ignore case, so "shirt" matches "T-Shirt".
const products = [{ name: "T-Shirt", price: 20 },{ name: "Sweatshirt", price: 45 },{ name: "Hat", price: 15 },{ name: "Shorts", price: 30 },]
Solution
const search = (items, term) => {const query = term.trim().toLowerCase()return items.filter((item) => item.name.toLowerCase().includes(query))}search(products, "shirt")// [{ name: "T-Shirt", price: 20 }, { name: "Sweatshirt", price: 45 }]search(products, "SH")// T-Shirt, Sweatshirt and Shorts
Lowercasing both the search term and the name makes the comparison case insensitive. This is the core of most client-side search inputs.
Exercise 2: Intersection of two arrays
Return the values that appear in both arrays.
const myFriends = ["John", "Jane", "Sam", "Alex"]const yourFriends = ["Sam", "Chris", "John", "Taylor"]
Solution
const mutualFriends = myFriends.filter((friend) => yourFriends.includes(friend))// ["John", "Sam"]
Flip the test with ! and you get the difference instead: the friends that are
only in myFriends.
const onlyMine = myFriends.filter((friend) => !yourFriends.includes(friend))// ["Jane", "Alex"]
Exercise 3: Filter and format
Return the products that are in stock and cost less than 50, formatted as
"Name - $Price".
const inventory = [{ name: "Keyboard", price: 45, inStock: true },{ name: "Monitor", price: 200, inStock: true },{ name: "Mouse", price: 25, inStock: false },{ name: "Webcam", price: 40, inStock: true },]
Solution
const deals = inventory.filter((item) => item.inStock && item.price < 50).map((item) => `${item.name} - $${item.price}`)// ["Keyboard - $45", "Webcam - $40"]
Filter first so you only format the items you actually need.
Exercise 4: Filter by date
Return only the posts published in 2020.
const posts = [{ title: "Debouncing", date: "2019-11-02" },{ title: "Promises", date: "2020-01-15" },{ title: "Classes", date: "2019-10-26" },{ title: "Filter", date: "2020-03-14" },]
Solution
const postsFrom2020 = posts.filter((post) => new Date(post.date).getUTCFullYear() === 2020)// [{ title: "Promises", ... }, { title: "Filter", ... }]
Converting the string to a Date gives you methods to compare against. A
date-only string like "2020-01-15" is parsed as UTC, so getUTCFullYear()
avoids it landing on the wrong year in your local time zone.
Pretty nifty how far one method can take you. Once these feel easy, try
combining filter with reduce or sort in the same chain.
Have some feedback on this post? .