The filter() method of the Array class in JavaScript returns a new array containing all elements of the calling array for which the provided filtering function returns true.
There are 2 variations for the syntax of Array.filter() method. They are:
filter(callbackFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
This method returns a new array containing all elements of the calling array for which the provided filtering function returns true.
Returns value of type Array
.
filter(callbackFn, thisArg)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackFn | required | A function to test each element in the array. It takes three arguments: element, index, and array. |
thisArg | optional | A value to use as this when executing callbackFn. |
This method returns a new array containing all elements of the calling array for which the provided filtering function returns true, using thisArg as the value of this inside callbackFn.
Returns value of type Array
.
In JavaScript, we can use the filter() method to filter out even numbers from an array.
For example,
const arr = [1, 2, 3, 4, 5, 6];
const isEven = element => element % 2 === 0;
const evenNumbers = arr.filter(isEven);
console.log(evenNumbers);
[2, 4, 6]
We can use the filter() method to filter out strings with length greater than 3 from an array.
For example,
const strArr = ['apple', 'bat', 'cat', 'dog'];
const isLengthGreaterThanThree = element => element.length > 3;
const longStrings = strArr.filter(isLengthGreaterThanThree);
console.log(longStrings);
['apple']
We can use the filter() method with a thisArg to filter elements in an array using a specific context.
For example,
const arr = [10, 20, 30, 40, 50];
const context = { threshold: 30 };
function isGreaterThanThreshold(element) {
return element > this.threshold;
}
const filteredArr = arr.filter(isGreaterThanThreshold, context);
console.log(filteredArr);
[40, 50]
In this JavaScript tutorial, we learned about filter() method of Array: the syntax and few working examples with output and detailed explanation for each example.