How to Use JavaScript Array Filter

How to Use JavaScript Array Filter

6 mins read714 Views Comment
Chanchal
Chanchal Aggarwal
Senior Executive Content
Updated on Dec 18, 2023 18:37 IST

The JavaScript array.filter() method creates a new array filled with elements that pass a test provided by a function. It's a powerful tool for quickly extracting subsets of data from arrays based on specific criteria, without altering the original array. This method is essential for tasks like searching, data manipulation, and dynamically displaying content based on conditions.

2022_11_Array-Filter.jpg

Imagine you have a list of students with their grades and you need to find those who passed. In JavaScript, the array.filter() method simplifies this task. By applying a condition like grade >= passingScore, filter() creates a new array of students who meet this criterion, efficiently segregating passers from the rest. Let's understand this JavaScript concept in detail. 

Explore: Online JavaScript Courses and Certifications 

Table of Contents

JavaScript Array Filter

The filter() method returns a new array of elements that pass a test a situation provides. It does not execute the function for the empty items.

The filter() does not make changes to the existing array.

Example:


 
const words = ['happy', 'square', 'confidence', 'mystery','scale','joyous'];
const result = words.filter(word => word.length > 5);
Copy code
Output: 
console.log(result); // expected output: Array ["happy", "scale"]

JavaScript Array – How to Use Them?
JavaScript Array – How to Use Them?
JavaScript arrays are versatile, ordered collections of elements that can hold items of any data type, including numbers, strings, or objects. They offer a range of methods for traversal, manipulation,...read more

15+ JavaScript Array Methods with Examples
15+ JavaScript Array Methods with Examples
JavaScript array methods offer powerful tools for manipulating arrays. Key methods include 'push()' and 'pop()' for adding/removing elements at the end, 'shift()' and 'unshift()' for operations at the beginning, 'map()'...read more

Syntax

array.filter(function(currentValue, index, arr), thisValue)

Parameters

1. function(): This parameter holds the function required for each array element.

2. CurrentValue: The value of the current array.

3. index: The index of the current element. It is an optional parameter.

4. arr: The array of the current element.

5. this value: It is an optional parameter which is default undefined. Functions receive this value as a parameter.

JavaScript Array Sort
JavaScript Array Sort
The JavaScript array.sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order, but a custom...read more

How to Find the JavaScript Array Length
How to Find the JavaScript Array Length
The length property of a JavaScript array returns the number of elements in the array, providing an easy way to determine its size. It's dynamic, meaning it updates as elements...read more

Return Value

When we use the function(), it returns the value that suits the particular set of conditions.

Examples Showing JavaScript Array Filter Use

Filtering out Values from an array

In this example, the filter() method creates a new array comprising of only those elements that fulfill the given condition checked by isBigEnough. The given problem requires values greater than 100 to be filtered.


 
function isBigEnough(value) {
return value >= 100;
}
const filtered = [97, 105, 182, 63, 147].filter(isBigEnough);
Copy code
Output:
 filtered is [105, 182, 147]

Explanation:

Function Declaration:

isBigEnough(value) is a function that takes a single argument value and returns true if the value is greater than or equal to 100, and false otherwise.

Original Array:

An array [97, 105, 182, 63, 147] contains a mix of numbers both below and above 100.

Applying filter():

The filter() method is called on this array. It iterates through each element of the array and applies the isBigEnough function to determine if an element should be included in the new array.

Filtering Process:

For each element, filter() checks if it is greater than or equal to 100 (using the isBigEnough function). If yes, the element is included in the new array; if not, it is excluded.

Output:

The resulting filtered array is [105, 182, 147]. These are the elements from the original array that meet the condition value >= 100.

Searching out Values

iPositive() function


 
function isPositive(value) {
return value > 10;
}
var filtered = [12, 2, 0, -15, 14].filter(isPositive);
print(filtered);
Copy code
Output: 
12, 14

Explanation:

Function Definition:

The isPositive(value) function is defined to check if a given value is greater than 10. It returns true if the condition is met (value is positive and greater than 10) and false otherwise.

Original Array:

The array [12, 2, 0, -15, 14] consists of a mix of positive and negative numbers, as well as numbers smaller than 10.

Applying filter():

The filter() method is called on the array, using isPositive as the test function. It iterates through each element in the array.

Filtering Process:

For each element in the array, filter() applies the isPositive function. If isPositive returns true for an element (meaning the element is greater than 10), the element is included in the new filtered array.

Result:

The resulting filtered array is [12, 14]. These are the elements from the original array that are greater than 10.

Output:

Finally, print(filtered); outputs the contents of the filtered array. Note that print is not a standard JavaScript function for output. In a typical JavaScript environment, console.log(filtered); would be used to display the output.

isEven() function


 
function isEven(value) {
return value % 2 == 0;
}
var filtered = [15, 48, 51, 79, 324].filter(isEven);
print(filtered);
Copy code
Output: 
48,324
Explanation:
Function Definition:
The isEven(value) function checks whether a given value is even. It uses the modulus operator (%)
to determine if the value is divisible by 2 without a remainder. If the value is even (value % 2 == 0),
the function returns true; otherwise, it returns false.
Original Array:
The array [15, 48, 51, 79, 324] contains a mix of even and odd numbers.
Applying filter():
The filter() method is called on this array, using isEven as the test function.
It iterates through each element of the array.
Filtering Process:
For each element, the filter() method applies the isEven function. If isEven returns true (meaning the
element is aneven number), the element is included in the new filtered array.
Result:
The resulting filtered array is [48, 324]. These are the elements from the original array
that are even numbers.
Output:
The line print(filtered); is intended to output the contents of the filtered array. In standard JavaScript,
you would use console.log(filtered); to display the output, which would show 48, 324.

Browsers that Support JavaScript Array Filter()

Various browsers support the array Filter() of JavaScript. Below are the names:

1. Microsoft Edge 9.0

2. Google Chrome

3. Mozilla Firefox 1.5

4. Safari

5. Opera

Explore popular online courses –  

Free JavaScript Courses Online Html Css Javascript Online Courses & Certifications
JavaScript Online Courses and Certifications The Complete JavaScript Course: Beginner to Advanced level

Conclusion

Using the JavaScript filter(), you can find the elements per the given condition. This function also returns the new arrays comprising elements that fulfil the given criteria. In the above blog, we discussed the use of JavaScript filter() and its significant concepts. 

FAQs

1. How do you filter an array in JavaScript?

The developer can use the JavaScript filter in the array to identify the element that matches the given condition. The filter function returns a new array comprising all the array elements per the function. If no elements are suitable, then it returns an empty array.

2. How does JavaScript array filter() work?

The JavaScript filter array functions provide a list of the elements that suit specific conditions. Once filtration is done, it returns the array values that meet the given condition. The JavaScipt filter returns only the values or items that are appropriate as per the specific condition.

3. What is the best way to filter between two arrays?

Using the following function, you can find the difference between two arrays: Array.prototype.filter()function- Using this function, you can find the element of the first array which is not present in the second array. jQuery- Developers can use the .not() method to know the difference.

4. Does the JS filter mutate the array?

The filter creates a new array, while mutationFilter does not. However, the entire scenario created a new array with Array.filter is generally required. One benefit of utilizing a mutated array is that developers can make through the array by reference without you would need to wrap the array inside another element.

5. What do you mean by filter() in JS?

The filter() method embeds a new array with items that match the given condition. The filter() method does not perform the function for empty elements. Additionally, it does not changes the existing array elements.

6. Is Filter faster than for loop JavaScript?

If we compare the Array.filer method with loops, they are much slower. The Filter method is 77% slower than for loop.

About the Author
author-image
Chanchal Aggarwal
Senior Executive Content

Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio