TypeScript 101 – the filter() method

TypeScript 101 - the filter() method

This is the second post of a blog series where each post will touch a popular TypeScript method, function or feature with example. If you’re starting with TypeScript (or JavaScript) you might not be familiar with all of these powerful tools that can shorten your codebase and help you in day to day development.

This post we will discuss the .filter() function.

.filter()

When you have an array but only want the items that match a certain criteria you can use filter(). Well basically it’s quite self explaining to filter those items out.

Let’s say an API call like:

const result = await ec2.describeInstances(param).promise();

Returns a list of EC2 instances in our AWS account which simplified looks like this:

const instances = [
        {
          'InstanceId':'i-1234567890a',
          'InstanceType':'t3.xlarge',
          'SubnetId':'subnet-123456',
          'VpcId':'vpc-987654',
          'Architecture':'x86_64'
        },
        {
          'InstanceId':'i-1234567890b',
          'InstanceType':'t3.small',
          'SubnetId':'subnet-123456',
          'VpcId':'vpc-987654',
          'Architecture':'x86_64'
        },
        {
          'InstanceId':'i-1234567890c',
          'InstanceType':'t3.small',
          'SubnetId':'subnet-123456',
          'VpcId':'vpc-987654',
          'Architecture':'x86_64'
        }
      ]

And we would like to continue in our code working with only the instances that match the instanceType = t3.small requirement.

The solution using the .filter() function would look like this:

const small = instances.filter(instance => instance.InstanceType === 't3.small');
console.log('instances: ', JSON.stringify(small));

Summary

So how does it work ? Well in this case if the .filter() finds a match the callback function will return true and the current element will be added to the resulting array.

Make sure to also check our other TypeScript 101 posts.

Hope it helps!