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 react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.

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 July 28, 2024 Interface vs Type alias in Typescript with some real-world examples showing when to use what

In TypeScript, both interface and type alias can be used to define the shape of an object. However, there are some differences and nuances between them. Here are the key differences:

Like my work?

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