Array filter() Method - TypeScript

Last Updated : 12 Jul, 2024

The Array.filter() method in TypeScript creates a new array with elements that pass the test provided by a callback function. It does not modify the original array and accepts an optional thisObject for context within the callback function.

Syntax

array.filter(callback[, thisObject])

Parameter: This method accepts two parameters as mentioned and described below:

  • callback: This parameter is the Function to test for each element.
  • thisObject: This is the Object to use as this parameter when executing callback.

Return Value: This method returns the created array. 

Below examples illustrate the Array filter() method in TypeScript

Example 1: Filtering an Array of Numbers

In this example we filters out numbers greater than 10 from the numbers array using the filter method

JavaScript
let numbers: number[] = [11, 23, 45, 89, 7, 98];
let filteredNumbers: number[] = numbers.filter((num) => num > 10);

console.log(filteredNumbers); 

Output: 

[ 11, 23, 45, 89, 98 ]

Example 2: Filtering an Array of Strings

In this example we filters out words with a length greater than 5 from the words array using the filter method, resulting in filteredWords array containing ["banana", "cherry"].

JavaScript
let words: string[] = ["apple", "banana", "cherry", "date"];
let filteredWords: string[] = words.filter((word) => word.length > 5);

console.log(filteredWords);  

Output:

[ 'banana', 'cherry' ]

Example 3: Using an Inline Callback Function

In this example we filters out even numbers from the numbers array using the filter method. The resulting filteredNumbers array contains [98]. This array is then logged to the console.

JavaScript
let numbers: number[] = [11, 23, 45, 89, 7, 98];
let filteredNumbers: number[] = numbers.filter(function (num) {
    return num % 2 === 0;
});

console.log(filteredNumbers);  

Output:

[ 98 ]

Example 4: Filtering an Array of Objects

In this example we filters out people older than 30 from the people array using the filter method.

JavaScript
interface Person {
    name: string;
    age: number;
}

let people: Person[] = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 35 },
    { name: "Dave", age: 40 }
];

let filteredPeople: Person[] = people.filter((person) => person.age > 30);

console.log(filteredPeople);  

Output:

[ { name: 'Charlie', age: 35 }, { name: 'Dave', age: 40 } ]
Comment

Explore