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.

ToDoBar

Your to-dos on your menu bar.

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 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 javascript November 14, 2024 !== null vs !== undefined in Typescript or Javascript, how to check for both at once?

The choice between !== undefined and !== null depends on the context and what you’re trying to check.