How to use filter in JavaScript - Filtering Arrays for Precision
Master JavaScript's filter method with coding challenges, step-by-step explanations, and real-world use cases. Learn how to efficiently filter arrays to get exactly the data you need.

What is Array filter in JavaScript?
Array.filter is a powerful array method in JavaScript that creates a new array containing elements that pass a specific test. Whether you're searching for specific items, removing unwanted data, or creating subsets of arrays, filter is an essential tool in every JavaScript developer's toolkit. It's perfect for when you need to extract specific elements from an array based on certain conditions.
1const numbers = [1, 2, 3, 4, 5, 6];2const evenNumbers = numbers.filter(num => num % 2 === 0);3console.log(evenNumbers); // [2, 4, 6]
In this example, we are filtering out all odd numbers from the array. The filter function takes a callback function as its argument. The callback function is called for each element in the array and should return true if we want to keep the element, or false if we want to exclude it.
The callback function takes the current element as its parameter (num in this case) and returns true if the number is even (num % 2 === 0). Filter creates a new array containing only the elements for which the callback returned true.
💡 Pro tip: filter always returns a new array and never modifies the original array. This is important for maintaining immutability in your applications.
1Array.filter(function(currentValue, index, arr), thisValue)
Let's break down each part of the filter syntax:
Array
- The array you want to filter.filter()
- The filter method called on the arrayfunction
- The callback function that determines which elements to keep- Parameters of the callback function:
currentValue
: The current element being processed (required)index
: The index of the current element (optional)arr
: The array that filter was called upon (optional)
thisValue
- Value to use as 'this' when executing the callback (optional)
For example:
1const numbers = [1, 2, 3, 4, 5];23// Basic usage with just currentValue4numbers.filter(num => num > 2); // [3, 4, 5]56// Using index parameter7numbers.filter((num, index) => index % 2 === 0); // [1, 3, 5]89// Using all parameters10numbers.filter((num, index, array) => {11return num > array[index - 1]; // Keep numbers larger than previous12}); // [2, 3, 4, 5]
The callback function must return either true or false for each element:
- Return
true
: The element will be included in the new filtered array - Return
false
: The element will be excluded from the new filtered array
Remember that filter always returns a new array and does not modify the original array.
The filter function is commonly used in modern web applications for:
- Filtering search results
- Data validation
- Removing unwanted elements
- Creating subsets of data
- Form filtering
- User interface filtering
Let's explore some real-world examples that you'll likely encounter in your development journey.
Example 1 - Filter products by price range
1// Filter products within a specific price range2const products = [3{ name: 'Laptop', price: 999.99 },4{ name: 'Headphones', price: 99.99 },5{ name: 'Mouse', price: 29.99 },6{ name: 'Keyboard', price: 59.99 }7];89const affordableProducts = products.filter(product => product.price < 100);10console.log(affordableProducts);11/* Output:12[13{ name: 'Headphones', price: 99.99 },14{ name: 'Mouse', price: 29.99 },15{ name: 'Keyboard', price: 59.99 }16]17*/
Let's break down what's happening in this example step by step:
-
First, we have an array of objects called
products
. Each object represents a product with two properties:name
: The name of the productprice
: The cost of that product
-
We use the filter method to create a new array containing only affordable products. Here's how it works:
- The callback function takes each product object as its parameter
- It returns true if the product's price is less than 100
- Filter creates a new array with only the products that passed the test
-
Let's see how each element is processed:
- Laptop: 999.99 < 100? false (excluded)
- Headphones: 99.99 < 100? true (included)
- Mouse: 29.99 < 100? true (included)
- Keyboard: 59.99 < 100? true (included)
💡 Pro tip: You can chain multiple filters together for more complex filtering conditions.
Example 2 - Filter users by age
1// Filter users who are old enough to vote2const users = [3{ name: 'Alice', age: 25 },4{ name: 'Bob', age: 17 },5{ name: 'Charlie', age: 21 },6{ name: 'David', age: 16 }7];89const canVote = users.filter(user => user.age >= 18);10console.log(canVote);11/* Output:12[13{ name: 'Alice', age: 25 },14{ name: 'Charlie', age: 21 }15]16*/
Let's break down this example:
- We start with an array of user objects:
1// Start with an array of user objects2const users = [3{ name: 'Alice', age: 25 },4{ name: 'Bob', age: 17 },5{ name: 'Charlie', age: 21 },6{ name: 'David', age: 16 }7];
- We use filter to create a new array containing only users who are 18 or older:
1const canVote = users.filter(user => user.age >= 18);
- The callback function returns:
- true for Alice (25 >= 18)
- false for Bob (17 >= 18)
- true for Charlie (21 >= 18)
- false for David (16 >= 18)
💡 Pro tip: When filtering objects, make sure to check if the property exists to avoid errors with undefined values.
Example 3 - Filter objects by multiple conditions
1// Filter active premium users2const users = [3{ name: 'Alice', isPremium: true, isActive: true },4{ name: 'Bob', isPremium: false, isActive: true },5{ name: 'Charlie', isPremium: true, isActive: false },6{ name: 'David', isPremium: true, isActive: true }7];89const activePremiumUsers = users.filter(user =>10user.isPremium && user.isActive11);12console.log(activePremiumUsers);13/* Output:14[15{ name: 'Alice', isPremium: true, isActive: true },16{ name: 'David', isPremium: true, isActive: true }17]18*/
Let's break down this example:
- First, we have an array of user objects with multiple properties:
1// Array of users with premium and active status2const users = [3{ name: 'Alice', isPremium: true, isActive: true },4{ name: 'Bob', isPremium: false, isActive: true },5{ name: 'Charlie', isPremium: true, isActive: false },6{ name: 'David', isPremium: true, isActive: true }7];
- We use filter with a callback that checks multiple conditions:
1const activePremiumUsers = users.filter(user => user.isPremium && user.isActive);
- Let's see how each user is evaluated:
- Alice: (true && true) = true (included)
- Bob: (false && true) = false (excluded)
- Charlie: (true && false) = false (excluded)
- David: (true && true) = true (included)
💡 Pro tip: You can make complex conditions more readable by breaking them into separate variables or functions.
Example 4 - Filter unique values
1// Filter unique values from an array2const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];34const unique = numbers.filter((value, index, array) =>5array.indexOf(value) === index6);7console.log(unique); // [1, 2, 3, 4, 5]
Let's break down this example:
- We start with an array containing duplicate values:
1const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];
- We use filter with all three parameters available to the callback:
1const unique = numbers.filter((value, index, array) => array.indexOf(value) === index);
- Let's examine how it works for each element:
- 1: indexOf(1) = 0, current index = 0 (true, keep it)
- First 2: indexOf(2) = 1, current index = 1 (true, keep it)
- Second 2: indexOf(2) = 1, current index = 2 (false, filter it out)
- First 3: indexOf(3) = 2, current index = 3 (false, filter it out)
- And so on...
💡 Pro tip: While this method works, consider using Set for better performance with large arrays: [...new Set(numbers)]
Example 5 - Filter falsy values
1// Remove falsy values from an array2const mixed = [0, 1, false, true, '', 'hello', null, undefined, NaN];34const truthyOnly = mixed.filter(Boolean);5console.log(truthyOnly); // [1, true, 'hello']
Let's break down this example:
- We start with an array containing various types of values:
1const mixed = [0, 1, false, true, '', 'hello', null, undefined, NaN];
- We use the Boolean function as our filter callback:
1const truthyOnly = mixed.filter(Boolean);
- Let's see how each value is evaluated:
- 0: false (excluded)
- 1: true (included)
- false: false (excluded)
- true: true (included)
- '': false (excluded)
- 'hello': true (included)
- null: false (excluded)
- undefined: false (excluded)
- NaN: false (excluded)
💡 Pro tip: This is a concise way to remove all falsy values, but be careful as it might remove legitimate zero values that you want to keep.
This example shows how to use filter to remove all falsy values from an array. The Boolean function is used as the callback, which automatically converts values to true or false.
Practice Questions
Below are some practice coding challenges to help you master the filter method in JavaScript.
How to Transform User Data Array into Summary Report using JavaScript Array Methods
Calculate Average Engagement Rate for Posts with High Views using JavaScript Array Methods
JavaScript: Understanding Chained Array Methods with Map, Filter, and Reduce Operations
JavaScript Array Chaining: Understanding map, filter, and reduce with Initial Value
How to Find the First Element in JavaScript Array That Matches a Condition
Additional Resources
- MDN Web Docs - Array.prototype.filter()
- JavaScript.info - Array methods
- React Documentation - Lists and Keys (for seeing filter in action with React)
Common Interview Questions
- What's the difference between filter and map?
- How would you implement filter using reduce?
- When would you use filter instead of a for loop?
Keep practicing with filter - it's one of the most commonly used array methods in JavaScript!
Learn to code, faster
Join 650+ developers who are accelerating their coding skills with TechBlitz.
Read related articles

How to use split() in JavaScript
Understand how to use split() in JavaScript to break strings into arrays fo...


What is array.at() in JavaScript?
Discover how array.at() makes working with arrays in JavaScript more intuit...


What is length in JavaScript?
Learn how to effectively use JavaScript's length property to work with stri...
