Juneikerc.com

How to use the JavaScript .filter() method with 7 practical examples

Featured image of the post: How to use the JavaScript .filter() method with 7 practical examples

Have you ever wanted to get only the elements from an array that meet a specific condition? For example, what if you want to retrieve only the even numbers from an array of numbers?

Thanks to JavaScript's .filter() method, you can create a new array with elements from the original array that pass a specific test (function).

In other words, the .filter() method allows you to filter elements in an array based on a condition.

In this article, you'll learn how the .filter() method in JavaScript works, along with 7 practical and real examples of how you can use it in your web projects.

What is the .filter() method in JavaScript?

The .filter() method is one of the methods that JavaScript provides for working with arrays. This method takes a function (called a callback function) as an argument, which is executed for each element in the array.

This function should return a boolean value (true or false) that indicates whether the element passes the test or not. The .filter() method returns a new array with the elements that return true.

The syntax of the .filter() method is as follows:

js
let newArray = array.filter(callback(element, index, array));

Where:

  • array is the array on which the method is applied.
  • callback is the function executed for each element in the array.
  • element is the current element of the array being processed.
  • index is the index of the current element of the array being processed.
  • array is the array on which the method is applied (the same as the first argument).

The .filter() method does not modify the original array, but instead, it creates a new one. Additionally, the .filter() method respects the order of elements in the original array.

Let's look at a simple example of how to use the .filter() method:

js
// We create an array of numbers
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// We create a callback function that returns true if the number is even
function isEven(number) {
return number % 2 === 0;
}
// We apply the .filter() method to the array of numbers using the callback function
let evenNumbers = numbers.filter(isEven);
// We display the result in the console
console.log(evenNumbers); // [2, 4, 6, 8]

As you can see, the .filter() method has returned a new array with only the even numbers from the original array.

Example 1: Filtering Objects by a Property

Let's assume we have an array of objects representing people with their names and ages.

We want to obtain a new array with only the adults (18 years or older).

To do this, we can use the .filter() method with a callback function that checks the age property of each object.

js
// We create an array of objects representing people
let people = [
{ name: "Ana", age: 25 },
{ name: "Beto", age: 17 },
{ name: "Carlos", age: 19 },
{ name: "Diana", age: 15 },
];
// We create a callback function that returns true if the person is an adult
function isAdult(person) {
return person.age >= 18;
}
// We apply the .filter() method to the array of people using the callback function
let adults = people.filter(isAdult);
// We display the result in the console
console.log(adults); // [{ name: "Ana", age: 25 }, { name: "Carlos", age: 19 }]

As you can see, it has returned a new array with only the adults from the original array.

Example 2: Filtering Elements Matching a Regular Expression

Let's assume we have an array of strings representing email addresses.

We want to obtain a new array with only the email addresses that have the domain "@gmail.com".

To do this, we can use the .filter() method with a callback function that uses a regular expression to check if the string matches the desired pattern.

js
// We create an array of strings representing email addresses
let emails = [
];
// We create a regular expression that matches the domain "@gmail.com"
let regex = /@gmail\.com$/;
// We create a callback function that returns true if the email matches the regular expression
function isGmail(email) {
return regex.test(email);
}
// We apply the .filter() method to the array of email addresses using the callback function
let gmails = emails.filter(isGmail);
// We display the result in the console
console.log(gmails); // ["[email protected]", "[email protected]"]

It has returned a new array with only the email addresses that have the domain '@gmail.com.'

Example 3: Filtering Elements that Meet a Numeric Condition

Let's assume we have an array of numbers representing students' grades in a class.

We want to obtain a new array with only the passing grades (greater than or equal to 5).

To do this, we can use the .filter() method with a callback function that compares the number to the desired threshold.

js
// We create an array of numbers representing students' grades
let grades = [4.5, 6.7, 3.2, 8.9, 5.4, 7.3, 4.8, 6.1];
// We create a callback function that returns true if the grade is passing
function isPassed(grade) {
return grade >= 5;
}
// We apply the .filter() method to the array of grades using the callback function
let passedGrades = grades.filter(isPassed);
// We display the result in the console
console.log(passedGrades); // [6.7, 8.9, 5.4, 7.3, 6.1]

Example 4: Filtering Unique Elements

Let's assume we have an array of numbers that contains some repeated elements. We want to obtain a new array with only the unique elements (i.e., removing the duplicated elements):

js
// We create an array of numbers that contains some repeated elements
let numbers = [1, 2, 3, 4, 5, 3, 2, 6, 7, 8, 9, 8];
// We create a callback function that returns true if the element is unique
function isUnique(element, index, array) {
return array.indexOf(element) === index;
}
// We apply the .filter() method to the array of numbers using the callback function
let uniqueNumbers = numbers.filter(isUnique);
// We display the result in the console
console.log(uniqueNumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 5: Filtering Falsy Elements

Let's assume we have an array of mixed values that can be truthy or falsy. We want to obtain a new array with only the falsy elements (those that evaluate to false in a boolean expression).

To do this, we can use the .filter() method with a callback function that returns the same element.

js
// We create an array of mixed values that can be truthy or falsy
let values = [0, 1, "", "Hello", null, true, undefined, false, NaN, 2];
// We create a callback function that returns the same element
function isFalsy(element) {
/* Thanks to the negation operator (!), it returns true if 'element' is 'falsy' and false if 'element' is 'truthy' */
return !element;
}
// We apply the .filter() method to the array of values using the callback function
let falsyValues = values.filter(isFalsy);
// We display the result in the console
console.log(falsyValues); // [0, "", null, undefined, false, NaN]

Example 6: Filtering elements that belong to another array

We have two arrays of numbers and we want to obtain a new array with only the elements from the first array that are also in the second array. In other words, we want to obtain the intersection of the two arrays.

We can use the .filter() method with a callback function that uses the .includes() method to check if the current element is in the other array.

js
// We create two arrays of numbers
let array1 = [1, 2, 3, 4, 5];
let array2 = [3, 4, 5, 6, 7];
// We create a callback function that returns true if the element is in the other array
function isInArray2(element) {
return array2.includes(element);
}
// We apply the .filter() method to the first array using the callback function
let intersection = array1.filter(isInArray2);
// We display the result in the console
console.log(intersection); // [3, 4, 5]

JavaScript’s .filter() method is highly versatile

I hope you have learned to use this method with confidence and efficiency. If you enjoyed this article, feel free to share it, and you can also reach out to me on Twitter with your feedback or any questions you may have. Thank you very much for reading! 😊

Juneiker Castillo freelance web developer

I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.

About me