Loading...

How to filter an Array based on a condition in Typescript?

question typescript
Ram Patra Published on July 20, 2024

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.

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on July 20, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question typescript August 1, 2024 How to bubble up errors or exceptions from one method to another in Typescript?

In TypeScript, you can “bubble up” errors or exceptions from one method to another by allowing exceptions to propagate through the call stack. Here’s how you can achieve this with examples:

question typescript March 26, 2025 ES6 vs ES2020 vs ESNext modules and which one should you use

The difference between ESNext, ES6/ES2015, ES2020, and other module options in TypeScript is mainly about which ECMAScript version’s module system is used. Here’s a breakdown:

question typescript javascript August 11, 2024 What is module inside compilerOptions in tsconfig.json and what to use?

The module option inside compilerOptions in the tsconfig.json file of a TypeScript project specifies the module code generation system that the TypeScript compiler should use when emitting JavaScript. This option determines how the TypeScript code will be transformed into JavaScript modules, affecting how modules are loaded, interpreted, and linked in the resulting JavaScript code.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.