Array.filter()
The Array.filter() method in JavaScript creates a new array with all elements that pass the test implemented by the provided callbackFn. It is often used to filter elements from an array based on specific conditions.
Syntax
filter(callbackFn)
filter(callbackFn, thisArg)
Parameters
| Parameter | Description |
|---|---|
callbackFn | A function used to test each element of the array. The function should return true to include the element in the new array or false to exclude it. It is called with three arguments: element, index, and array. |
thisArg | Optional. An object to use as this when executing callbackFn. |
Return Value
The filter() method returns a new array containing all elements of the original array that satisfy the condition implemented by callbackFn. If no elements satisfy the condition, it returns an empty array.
Examples
1. Filtering Numbers Greater than a Certain Value
This example demonstrates filtering an array of numbers to include only those greater than 10.
const numbers = [5, 12, 8, 130, 44];
const filtered = numbers.filter(num => num > 10);
console.log(filtered);
Output
[12, 130, 44]
filter()processes each element innumbersand includes it in the result only if the conditionnum > 10evaluates totrue.
2. Filtering Even Numbers
The following example filters an array to include only even numbers.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens);
Output
[2, 4, 6]
3. Filtering Objects in an Array
This example filters an array of objects to include only those with a specific property value.
const users = [
{ name: "Akash", age: 25 },
{ name: "Bhairav", age: 17 },
{ name: "Charlie", age: 19 }
];
const adults = users.filter(user => user.age >= 18);
console.log(adults);
Output
[ { name: 'Akash', age: 25 }, { name: 'Charlie', age: 19 } ]
- The
filter()method iterates through each object inusersand includes it in the result only if the conditionuser.age >= 18evaluates totrue.
4. Using thisArg with filter()
You can pass a thisArg to use as the this context inside callbackFn.
const threshold = { limit: 15 };
const numbers = [10, 20, 30, 5];
const filtered = numbers.filter(function(num) {
return num > this.limit;
}, threshold);
console.log(filtered);
Output
[20, 30]
Here, this.limit references the limit property of the threshold object passed as thisArg.
