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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

KeyScreen

Show keypresses on your screen.

ToDoBar

Your to-dos on your menu bar.

SimpleFill

Fill forms using your right-click menu.

IconSim

Preview your Mac app icons.

Ram Patra Published on July 20, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question typescript javascript July 17, 2024 Difference between ?? and || in Typescript or Javascript?

In TypeScript (and JavaScript), the ?? (nullish coalescing operator) and || (logical OR operator) are both used to provide default values, but they behave differently in terms of the conditions under which they return the right-hand operand.

question typescript November 21, 2024 How to parse string to boolean in Typescript?

In TypeScript, parsing a string to a boolean typically involves converting specific string values (e.g., "true" or "false") to their corresponding boolean values. Here’s how you can do it:

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:

Like my work?

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