Filtering an array based on a condition in TypeScript is straightforward and similar to how you would do it in JavaScript. TypeScript adds type safety to the process, ensuring that your code is more robust and less error-prone.
Here’s a step-by-step guide on how to filter an array in TypeScript:
Basic Filtering Example
Suppose you have an array of numbers and you want to filter out all numbers that are greater than or equal to 50.
1. Define the Array
First, create an array of numbers:
const numbers: number[] = [10, 60, 40, 90];
2. Filter the Array
Use the filter
method to create a new array containing only the elements that meet your condition. In this case, you want numbers that are greater than or equal to 50:
const filteredNumbers: number[] = numbers.filter(num => num >= 50);
3. Log the Result
You can then log or use the filtered array as needed:
console.log(filteredNumbers); // Output: [60, 90]
Filtering with Objects
If you have an array of objects and you want to filter based on a property, the approach is similar.
Example: Filtering Objects
Suppose you have an array of objects representing users, and you want to filter users who are above 18 years old.
interface User {
name: string;
age: number;
}
const users: User[] = [
{ name: 'Alice', age: 22 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 30 },
];
const adults: User[] = users.filter(user => user.age > 18);
console.log(adults);
// Output: [ { name: 'Alice', age: 22 }, { name: 'Charlie', age: 30 } ]
Using Generics for More Flexibility
If you want a more flexible solution where you can specify the type of array elements, you can use TypeScript generics:
function filterArray<T>(array: T[], predicate: (item: T) => boolean): T[] {
return array.filter(predicate);
}
// Example usage with numbers
const numbers: number[] = [10, 60, 40, 90];
const filteredNumbers = filterArray(numbers, num => num >= 50);
console.log(filteredNumbers); // Output: [60, 90]
// Example usage with objects
const users: User[] = [
{ name: 'Alice', age: 22 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 30 },
];
const adults = filterArray(users, user => user.age > 18);
console.log(adults); // Output: [ { name: 'Alice', age: 22 }, { name: 'Charlie', age: 30 } ]
Summary
- Basic Filtering: Use the
filter
method with a condition. - Filtering Objects: Apply the
filter
method with a predicate that checks object properties. - Generics: For reusable filtering functions, use TypeScript generics to handle different types of arrays.
These techniques ensure that your filtering operations are type-safe and easy to manage in TypeScript.