Published on

TypeScript: How to Filter Objects in an Array

Filtering objects in an array is a common task in programming. In TypeScript, you can use the Array.filter() method to filter objects in an array based on a condition. This method creates a new array with all the elements that pass the test implemented by the provided function.

Example:

ts-array-filter.tsx
interface Member {
  fullName: string
  subscriptionID: number
}

const members: Member[] = [
  { fullName: 'Mike Doe', subscriptionID: 1 },
  { fullName: 'Johnny Smith', subscriptionID: 2 },
  { fullName: 'Alex Johnson', subscriptionID: 3 },
]

// Example 1: Filter members by subscription ID
const filteredMembers1: Member[] = members.filter((member) => member.subscriptionID === 1)
console.log(filteredMembers1)
// Returns [{ fullName: 'Mike Doe', subscriptionID: 1 }]

// Example 2: Filter members by full name
const filteredMembers2: Member[] = members.filter((member) => member.fullName.includes('John'))
console.log(filteredMembers2)
// Returns [{ fullName: 'Johnny Smith', subscriptionID: 2 },{ fullName: 'Alex Johnson', subscriptionID: 3 }]

In conclusion, filtering objects in an array using TypeScript is a powerful feature that can be accomplished using the Array.filter() method. By applying different conditions to the filter() method, we can return a new array with only the elements that meet our criteria.