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

</>
Copy
filter(callbackFn)
filter(callbackFn, thisArg)

Parameters

ParameterDescription
callbackFnA 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.
thisArgOptional. 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.

</>
Copy
const numbers = [5, 12, 8, 130, 44];

const filtered = numbers.filter(num => num > 10);
console.log(filtered);

Output

[12, 130, 44]
  1. filter() processes each element in numbers and includes it in the result only if the condition num > 10 evaluates to true.

2. Filtering Even Numbers

The following example filters an array to include only even numbers.

</>
Copy
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.

</>
Copy
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 } ]
  1. The filter() method iterates through each object in users and includes it in the result only if the condition user.age >= 18 evaluates to true.

4. Using thisArg with filter()

You can pass a thisArg to use as the this context inside callbackFn.

</>
Copy
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.