Definition and Usage
The filter()
function for arrays filters elements of an array using a callback function.
Using this function, you can easily filter an array to keep only the values you want.
By writing the condition as a callback function, it returns a new array containing only the elements that satisfy the condition.
Features
- The filtering condition is applied in a callback function:
The callback should returntrue
for elements that meet the condition, andfalse
for those that do not. - The original array is not modified. Instead, the function returns a new array containing only the elements that pass the filter.
Basic Example
Let's explain this with a simple example.
The following example uses the filter()
function to return a new array containing only the even numbers from an existing array.
// Array to filter
const num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Callback function defined by the developer
function isEven(value) {
return value % 2 === 0; // Returns true if the value is even
}
// Filter the array elements using the callback function
const result = num.filter(isEven);
console.log(result); // Output: [2, 4, 6, 8, 10]
As shown in the example, the callback function evaluates a condition for each element.
To keep an element in the filtered array, the callback should return true
; otherwise, it should return false
.
The filter()
function iterates through each element and collects only those elements for which the callback returns true
into a new array.
filter()
function works:
/* The filter() function is used to
select only the elements that meet a certain condition from an array. */
// For example, filtering only lowercase letters from an array
['a', 'B', 'c', 'D'].filter(isLowerCase) 👉 ['a', 'c']
Syntax
arr.filter(callbackFn[, thisArg])
arr
is the array to which the filter()
function is applied.
Parameters
callbackFn |
Required. A callback function that is called for each element of the array.
The callback receives the current element as an argument and should return
true or false . Returning true includes
the element in the new filtered array, while returning false excludes it.
Callback function parameters: callbackFn(element[, index[, array]])
|
---|---|
thisArg |
Optional. A value to use as this when executing callbackFn . |
The first parameter, callbackFn
, can be written in several forms depending on the function syntax:
// Arrow function
filter((element) => { /* … */ })
filter((element[, index]) => { /* … */ })
filter((element[, index[, array]]) => { /* … */ })
// Callback function reference
filter(callbackFn)
filter(callbackFn[, thisArg])
// Inline callback function
filter(function (element) { /* … */ })
filter(function (element[, index]) { /* … */ })
filter(function (element[, index[, array]]) { /* … */ })
filter(function (element[, index[, array]]) { /* … */ }[, thisArg])
Return Value
The filter()
function returns a new array containing only the elements that meet the specified condition. If no elements satisfy the condition, it returns an empty array.
How the Callback Function Works
callbackFn(element[, index[, array]])
The filter()
function uses a developer-defined callback function to evaluate each element of an array. It returns a new filtered array containing only the elements that meet the specified condition.
The callback function is called for each element of the array. Depending on the return value of the callback (true
or false
), an element is either included in or excluded from the filtered array.
Below is a step-by-step explanation of how the filter()
callback function is invoked.
filter()
/**
* Callback function
*
* @param {*} element The current array element
* @param {number} index Optional. The index of the current element
* @param {Array} array Optional. The original array
* @return {boolean} Return true if the element meets the filtering condition, false otherwise
*
* The callback can be a named function (user-defined) or an anonymous function.
* It can also be written as an arrow function.
*/
// Using a named function
function callbackFn(element[, index[, array]]) {
// Filtering logic: return a boolean to determine if the element should be included
}
arr.filter(callbackFn); // Pass the named function as the parameter
// Using an anonymous function
arr.filter(function (element[, index[, array]]) {
// Filtering logic: return a boolean to determine if the element should be included
});
How filter()
Works Step by Step:
- When calling
filter()
, the array to be filtered is passed to the callback function. filter()
selects the first element of the array and passes it as the first argument (element
) to the callback function.- The callback function executes, and the element can be used within it. Apply the necessary condition and use
return
to indicate whether the element meets the filtering condition. - If the callback returns
true
, the element is included in the filtered array; if it returnsfalse
, the element is excluded. filter()
moves on to the next element and repeats this process.- After all elements have been processed,
filter()
returns a new array containing only the elements for which the callback returnedtrue
. - The resulting array includes only those elements that satisfied the condition.
By following this process, the callback function allows filter()
to selectively return elements from the original array. Since the developer defines the filtering condition, filter()
can be used for a wide variety of filtering tasks.
Practical Examples
The filter()
function can be used for a variety of array filtering tasks. Here are some examples.
Removing Duplicate Elements from an Array
Removing duplicates using the filter()
function requires a slightly more complex approach. Typically, two arrays are used to check for duplicates and remove them. The example below shows how to remove duplicate elements using filter()
.
filter()
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((element, index, arr) => {
// Return true only if the element has not appeared before
return arr.indexOf(element) === index;
});
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
Code Explanation
The indexOf()
function for arrays returns the index of the first occurrence of a given element in an array.
In the example above, indexOf()
is used to check if an element has already appeared in the numbers
array.
The condition arr.indexOf(element) === index
returns true
only if the element appears for the first time at the current index.
filter()
iterates over the array and returns a new array containing only the elements that satisfy the condition.
Filtering with Multiple Conditions
When using multiple conditions, you can combine them within the callback function. For example, to filter only even numbers that are less than 5 from an array:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredNumbers = numbers.filter(element => {
// Combine multiple conditions
return element % 2 === 0 && element < 5;
});
console.log(filteredNumbers); // Output: [2, 4]
The condition element % 2 === 0 && element < 5
returns true
only for elements that are even and less than 5.
Filtering a Two-Dimensional Array
Here is a simple example of filtering elements from a two-dimensional array. We create a students
array and filter only those students whose age is 30 or older.
const students = [
["Alice", 25],
["Bob", 30],
["Charlie", 22],
["David", 35]
];
const filteredStudents = students.filter(student => {
// Return true only if the second element (age) is 30 or older
return student[1] >= 30;
});
console.log(filteredStudents); // Output: [["Bob", 30], ["David", 35]]
In this example, filter()
iterates over the students
array and returns a new array containing only the sub-arrays where the second element (age) is 30 or older.
Filtering Strings with Length ≥ 5
const words = ["apple", "banana", "cherry", "date", "fig"];
const longWords = words.filter(word => word.length >= 5);
console.log(longWords); // Output: ["apple", "banana", "cherry"]
Code Explanation
The length
property returns the number of elements in an array (or characters in a string).
These examples demonstrate various ways to use the filter()
function. You can apply filter()
to arrays to select elements according to any condition you define.
Specifications
Specification | |
---|---|
filter()
|
ECMAScript Language Specification #sec-array.prototype.filter |
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
filter()
|
1 | 12 | 1.5 | 3 |