Syntax of the JavaScript Array filter() Method
Understanding the filter() method's syntax is like learning the basic rules of a game – it sets the foundation for how to use it effectively. The syntax of the filter() method is straightforward & follows a simple pattern:
array.filter(function(currentElement, index, arr), thisValue)
Here's what each part means:
-
array: This is the array you want to filter.
-
function(currentElement, index, arr): A function that runs for each element in the array. It takes up to three arguments:
-
currentElement: The current element being processed in the array.
-
index (Optional): The index of the current element being processed.
-
arr (Optional): The array the filter() method was called upon.
-
thisValue (Optional): A value to use as this when executing the function.
Only the currentElement is required. The function returns true for elements that should be included in the new array & false for those that shouldn't.
Example
Consider an array of numbers:
JavaScript
const numbers = [1, 2, 3, 4, 5];
To filter out even numbers:
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output
[2, 4]
In this example, filter() calls the function for each number in the numbers array. The function returns true for even numbers (num % 2 === 0) & false for odd numbers. As a result, evenNumbers contains only the even numbers from the original array.
Parameters of the JavaScript Array filter() Method
When you use the filter() method, you can provide it with up to three pieces of information, known as parameters, for each item in your array. These parameters give you more control over the filtering process. Let's break them down:
currentElement
This is the element from your array that filter() is currently looking at. It's like focusing on one piece of a puzzle at a time to decide if it fits in your picture.
index (Optional)
This tells you the position of the current element in the array. Knowing the position can be handy, like when you need to skip over certain items based on where they are in the list.
arr (Optional)
This gives you the entire array that you're working with. Sometimes, to make a decision about one item, you need to see the big picture and compare it to others in the list.
Example
Let's say you have a list of names and you want to filter out names that are too short. At the same time, you want to make sure the name isn't the first one in the list, regardless of its length.
JavaScript
const names = ["Akash", "Abhishek", "Ankush", "Aman"];
const filteredNames = names.filter((name, index) => {
return name.length >= 3 && index > 0;
});
console.log(filteredNames);

You can also try this code with Online Javascript Compiler
Run Code
Output
["Abhishek", "Ankush", "Aman"]
In this example, filter() looks at each name and its position in the list. It keeps names that are at least three characters long and are not the first item in the array.
Return Value of the JavaScript Array filter() Method
The filter() method in JavaScript gives you back a new array after it's done looking through the original one. This new array only includes items that passed the test set by your function. If no items pass the test, filter() will give you an empty array. It's like getting the results of an exam, where only the passing answers are handed back to you.
Example
Imagine you have an array of numbers, and you only want to keep the numbers greater than 10:
JavaScript
const numbers = [5, 12, 18, 1, 3];
const filteredNumbers = numbers.filter(number => number > 10);
console.log(filteredNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output
[12, 18]
In this example, filter() checks each number. If a number is more than 10, it gets added to filteredNumbers. So, you end up with an array that only includes 12 and 18, since those are the numbers greater than 10.
This shows how filter() can be a powerful tool for sorting through data and keeping only what you need. Whether you're dealing with numbers, strings, or more complex data, understanding the return value of filter() helps you write cleaner, more efficient JavaScript code.
Examples of Using the JavaScript Array filter() Method
Let's talk about practical examples to see how the filter() method can be used in different scenarios. These examples will help you grasp how versatile filter() can be for various tasks.
Example 1: Filtering Odd Numbers
Suppose you have an array of numbers and you want to create a new array that only includes the odd numbers.
JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const oddNumbers = numbers.filter(number => number % 2 !== 0);
console.log(oddNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output
[1, 3, 5, 7, 9]
Here, filter() checks each number with number % 2 !== 0 to find out if it's odd. If it is, the number gets added to the oddNumbers array.
Example 2: Filtering Words by Length
Imagine you have an array of words, and you want to find words that are longer than 4 characters.
JavaScript
const words = ["sun", "planet", "galaxy", "universe", "moon", "star"];
const longWords = words.filter(word => word.length > 4);
console.log(longWords);

You can also try this code with Online Javascript Compiler
Run Code
Output
["planet", "galaxy", "universe"]
In this case, filter() looks at the length of each word with word.length > 4. Words that are longer than 4 characters are kept in the longWords array.
Example 3: Filtering Objects Based on Properties
Let's say you have an array of objects, where each object represents a person with a name and age. You want to filter out people who are 18 years or older.
JavaScript
const people = [
{ name: "Alice", age: 17 },
{ name: "Bob", age: 20 },
{ name: "Charlie", age: 16 },
{ name: "Diana", age: 25 }
];
const adults = people.filter(person => person.age >= 18);
console.log(adults);

You can also try this code with Online Javascript Compiler
Run Code
Output
[{ name: "Bob", age: 20 }, { name: "Diana", age: 25 }]
In this example, filter() is used to check the age property of each object. People who are 18 or older are included in the adults array.
Supported Browsers
The good news is, the JavaScript filter() method works in almost all web browsers you might use. For example-:
Google Chrome
Fully supported across all recent versions.
Mozilla Firefox
Supported in all modern versions.
Apple Safari
Compatibility with all recent versions.
Microsoft Edge
Full support in all versions.
Internet Explorer
Supported from version 9 onwards; earlier versions require a polyfill for compatibility.
Frequently Asked Questions
Can filter() change the original array?
No, filter() does not change the original array. Instead, it creates a new array with elements that pass the test in the provided function. The original array stays the same, which is great for preventing unexpected changes to your data.
What happens if no elements pass the filter() test?
If none of the elements in the array pass the test implemented by your function, filter() will return an empty array. This means you'll end up with a new array that has no items in it, but your original array will still be intact.
Can I use filter() with objects instead of simple values?
Yes, you can use filter() on arrays of objects. You'll need to provide a function that tests each object based on its properties. This is useful for filtering data based on criteria like age, name, or any other property your objects might have.
Conclusion
The JavaScript filter() method is a powerful tool for working with arrays. It allows you to create new arrays filled only with elements that meet certain criteria, without altering the original array. This method is widely supported across modern web browsers, making it a reliable choice for developers. Through practical examples, we've seen how filter() can be applied to various scenarios, from filtering numbers and words to working with arrays of objects. Understanding how to use filter() effectively can greatly enhance your ability to manage and manipulate data in JavaScript, making your code more efficient and your applications more dynamic.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.