Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why We Use JavaScript Array filter() Method
2.1.
Example:
3.
Syntax of the JavaScript Array filter() Method
3.1.
Example
3.2.
JavaScript
4.
Parameters of the JavaScript Array filter() Method
4.1.
currentElement
4.2.
index (Optional)
4.3.
arr (Optional)
4.4.
Example
4.5.
JavaScript
5.
Return Value of the JavaScript Array filter() Method
5.1.
Example
5.2.
JavaScript
6.
Examples of Using the JavaScript Array filter() Method
6.1.
Example 1: Filtering Odd Numbers
6.2.
JavaScript
6.3.
Example 2: Filtering Words by Length
6.4.
JavaScript
6.5.
Example 3: Filtering Objects Based on Properties
6.6.
JavaScript
7.
Supported Browsers
7.1.
Google Chrome
7.2.
Mozilla Firefox
7.3.
Apple Safari
7.4.
Microsoft Edge
7.5.
Internet Explorer
8.
Frequently Asked Questions
8.1.
Can filter() change the original array?
8.2.
What happens if no elements pass the filter() test?
8.3.
Can I use filter() with objects instead of simple values?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Javascript Filter

Author Rahul Singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

The JavaScript filter() method is a function used with arrays to create a new array filled with elements that pass a certain test defined by a provided function. It checks each element in the original array against the test; if the element meets the criteria, it's included in the new array, otherwise, it's excluded. This method doesn't change the original array, making it a super tool for filtering data without altering the original dataset.

Javascript Filter

In this article, we'll explore the ins & outs of filter(), its syntax, how & why to use it, practical examples, supported browsers, & more. 

Why We Use JavaScript Array filter() Method

When dealing with arrays in JavaScript, we often need to pick out elements that meet certain criteria. That's where the filter() method shines. It scans through an array & applies a test to each element. Elements that pass this test are added to a new array, leaving the original array unchanged.

This method is incredibly useful for tasks like:

  • Filtering search results based on user input
     
  • Removing unwanted data from a dataset
     
  • Creating subsets of data for analysis or display
     

Let's say you have a list of students with their grades, & you want to find out who passed. Using filter(), you can easily create a list of passing students without having to write cumbersome for-loops & temporary arrays. It simplifies your code, making it more readable & maintainable.

Example:

Imagine an array of student grades:

const grades = [65, 70, 80, 55, 90, 58];

To filter out passing grades (let's say 60 & above):

const passingGrades = grades.filter(grade => grade >= 60);
console.log(passingGrades); 

Output

[65, 70, 80, 90]


In this example, filter() checks each grade against the condition grade >= 60. Only grades that meet this condition are added to the new passingGrades array.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

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);

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

JavaScript

const names = ["Akash", "Abhishek", "Ankush", "Aman"];

const filteredNames = names.filter((name, index) => {

 return name.length >= 3 && index > 0;

});

console.log(filteredNames);

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

JavaScript

const numbers = [5, 12, 18, 1, 3];

const filteredNumbers = numbers.filter(number => number > 10);

console.log(filteredNumbers);

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

JavaScript

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const oddNumbers = numbers.filter(number => number % 2 !== 0);

console.log(oddNumbers);

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

JavaScript

const words = ["sun", "planet", "galaxy", "universe", "moon", "star"];

const longWords = words.filter(word => word.length > 4);

console.log(longWords);

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

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);

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 DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Sort Array Of Objects Javascript
Next article
Javascript And Operator
Live masterclass