TypeScript filter() Example: Filter Array of Objects by Property

In TypeScript, the filter() method allows us to create a new array from an existing array by selecting elements based on a provided condition. This article explores the syntax, examples and explanation of the filter() method in TypeScript.

// 1. Filter Array of Values
const numArray: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const evenNumArray = numArray.filter(n => n % 2 === 0);   // [2, 4, 6, 8, 10]

// 2. Filter Array of Objects
const people: Person[] = [{ name: "Alice", age: 25 }, ...];
const adults = people.filter((person) => person.age >= 18);

1. The ‘filter()’ Method in TypeScript

In TypeScript, filter(testFunction) is a built-in function available for arrays. It creates a new array that contains all elements from the original array that satisfy a given condition. Note that the original array remains unchanged.

const newArray = array.filter(testFunction(element[, index[, array]])[, thisArg]);
  • testFunction: The function used to test each element of the array. It should return true for elements that should be included in the new array.
  • element: The current element being processed in the array.
  • index (optional): The index of the current element in the array.
  • array (optional): The array on which the filter() method was called.
  • thisArg (optional): The value to use as this when executing the callback function.
const numArray: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

// 1. Using predicate
const evenNumArray = numArray.filter(n => n % 2 === 0);   // [2, 4, 6, 8, 10]

// 2. Using testFunction
function isEven(n: number) {  
    return n % 2 === 0;
}
const evenNumArray = numArray.filter(isEven);  // [2, 4, 6, 8, 10]

2. Filter Array of Strings

In the given example, we are checking each string in the array and discarding it if it starts with “test”.

const names = ["alex", "brian", "testName", "charles", "testD"];

const validNames = names.filter(str => !str.toLowerCase().startsWith("test"));  //Output ["alex", "brian", "charles"]

3. Filter Array by Object Property

Suppose we have an array of Employee objects and want to find all employees earning more than 5k USD.

const employees = [
  {id: 1, name: "alex", salary: 4000},
  {id: 2, name: "brian", salary: 5000},
  {id: 3, name: "charles", salary: 6000},
  {id: 4, name: "david", salary: 7000},
  {id: 5, name: "emily", salary: 2000}
];

const selectedEmployees = employees.filter(e => e.salary > 5000);

// Output [{id: 3, name: "charles", salary: 6000}, {id: 4, name: "david", salary: 7000}]

4. Filter Array for Null and Undefined

The array may contain null or undefined as values in some indices. We need to be careful when processing such arrays because they may break the program in runtime.

One possible way to cleanly filter out null or undefined values if defining a custom notEmpty() and using it everywhere we want to check a value. If we use generic type T then we can reuse this function for all kind of array types and other similar usecases.

function notEmpty<T>(value: T | null | undefined): value is T {
    return value !== null && value !== undefined;
}

For example, we can filter out null and undefined values from a string array as follows:

const names = ["alex", "brian", "charles", undefined, null];

const validNames = names.filter(str => notEmpty(str));   //Prints ["alex", "brian", "charles"]

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode