Back to blog

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.
6 min readLogan FordLogan Ford

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.


Let's take a look at a simple example:

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.

Syntax:

1Array.filter(function(currentValue, index, arr), thisValue)

Let's break down each part of the filter syntax:

  1. Array - The array you want to filter
  2. .filter() - The filter method called on the array
  3. function - The callback function that determines which elements to keep
  4. 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)
  5. thisValue - Value to use as 'this' when executing the callback (optional)

For example:

1const numbers = [1, 2, 3, 4, 5];
2
3// Basic usage with just currentValue
4numbers.filter(num => num > 2); // [3, 4, 5]
5
6// Using index parameter
7numbers.filter((num, index) => index % 2 === 0); // [1, 3, 5]
8
9// Using all parameters
10numbers.filter((num, index, array) => {
11return num > array[index - 1]; // Keep numbers larger than previous
12}); // [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.

Use Cases:

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 range
2const 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];
8
9const 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:

  1. First, we have an array of objects called products. Each object represents a product with two properties:

    • name: The name of the product
    • price: The cost of that product
  2. 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
  3. 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 vote
2const users = [
3{ name: 'Alice', age: 25 },
4{ name: 'Bob', age: 17 },
5{ name: 'Charlie', age: 21 },
6{ name: 'David', age: 16 }
7];
8
9const 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:


  1. We start with an array of user objects:
1// Start with an array of user objects
2const users = [
3{ name: 'Alice', age: 25 },
4{ name: 'Bob', age: 17 },
5{ name: 'Charlie', age: 21 },
6{ name: 'David', age: 16 }
7];

  1. We use filter to create a new array containing only users who are 18 or older:
1const canVote = users.filter(user => user.age >= 18);

  1. 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 users
2const 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];
8
9const activePremiumUsers = users.filter(user =>
10user.isPremium && user.isActive
11);
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:


  1. First, we have an array of user objects with multiple properties:
1// Array of users with premium and active status
2const 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];

  1. We use filter with a callback that checks multiple conditions:
1const activePremiumUsers = users.filter(user => user.isPremium && user.isActive);

  1. 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 array
2const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];
3
4const unique = numbers.filter((value, index, array) =>
5array.indexOf(value) === index
6);
7console.log(unique); // [1, 2, 3, 4, 5]

Let's break down this example:


  1. We start with an array containing duplicate values:
1const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5];

  1. We use filter with all three parameters available to the callback:
1const unique = numbers.filter((value, index, array) => array.indexOf(value) === index);

  1. 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 array
2const mixed = [0, 1, false, true, '', 'hello', null, undefined, NaN];
3
4const truthyOnly = mixed.filter(Boolean);
5console.log(truthyOnly); // [1, true, 'hello']

Let's break down this example:


  1. We start with an array containing various types of values:
1const mixed = [0, 1, false, true, '', 'hello', null, undefined, NaN];

  1. We use the Boolean function as our filter callback:
1const truthyOnly = mixed.filter(Boolean);

  1. 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
Medium
ArraysMapFilter+1
Calculate Average Engagement Rate for Posts with High Views using JavaScript Array Methods
Easy
ArraysFilterReduce+1
JavaScript: Understanding Chained Array Methods with Map, Filter, and Reduce Operations
Easy
JavascriptMapFilter+1
JavaScript Array Chaining: Understanding map, filter, and reduce with Initial Value
Medium
ArraysJavascriptMap+2
How to Find the First Element in JavaScript Array That Matches a Condition
Easy
ArraysMapFilter+3

Additional Resources

Common Interview Questions

  1. What's the difference between filter and map?
  2. How would you implement filter using reduce?
  3. 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.

Share this article