The filter() method in JavaScript creates a new array with all elements that pass the test implemented by the provided function. It does not modify the original array.
Syntax
array.filter(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback | A function to test each element of the array. It takes three arguments: element, index, and array. |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array filter() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Array | A new array with the elements that pass the test function. |
Example 1: Filtering Even Numbers
This code demonstrates how to use the filter() method to filter out even numbers from an array.
let Arr = [1, 2, 3, 4, 5, 6]; let evenNumbers = Arr.filter(function(element) { return element % 2 === 0; }); console.log(evenNumbers);
Output:
[ 2, 4, 6 ]
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let Arr = [1, 2, 3, 4, 5, 6]; let evenNumbers = Arr.filter(element => element % 2 === 0); console.log(evenNumbers);
Output:
[ 2, 4, 6 ]
Example 3: Filtering Strings by Length
This code demonstrates how to use the filter() method to filter out strings with a length greater than 3.
let strings = ["hello", "world", "javascript", "code"]; let filteredStrings = strings.filter(element => element.length > 3); console.log(filteredStrings);
Output:
[ "hello", "world", "javascript" ]
Example 4: Using a Provided thisArg
This code demonstrates how to use the filter()
method with a provided thisArg
to access a variable outside the callback function.
let fruits = ["apple", "banana", "cherry"]; let filterByLength = function(element) { return element.length === this.length; }; let filteredFruits = fruits.filter(filterByLength, { length: 5 }); console.log(filteredFruits);
Output:
[ "apple" ]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |