TypeScript 101 – the map() method

TypeScript 101 - the map() method

This is the start 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 .map() function.

.map()

We all been there that your receive an array of items being an input or response of an API call, but the only thing you need in the end is 1 value of each item.

Let’s start with an example where this code:

const ec2 = new EC2();

const param: EC2.Types.DescribeTagsRequest = {
 	Filters: [
        { Name: 'tag:Name', Values: [ 'nodes.k8s.terra10.nl' ] },
		{ Name: 'resource-type' , Values: [ 'instance' ]}
    ]
};
const result = await ec2.describeTags(param).promise();
console.log('Result: ', JSON.stringify(result));

returns a list of EC2 instances in our AWS account.

{
   "Tags":[
      {
         "Key":"Name",
         "ResourceId":"i-024dacbar12271337",
         "ResourceType":"instance",
         "Value":"nodes.k8s.terra10.nl"
      },
      {
         "Key":"Name",
         "ResourceId":"i-024dacbar12271338",
         "ResourceType":"instance",
         "Value":"nodes.k8s.terra10.nl"
      },
      {
         "Key":"Name",
         "ResourceId":"i-024dacbar12271339",
         "ResourceType":"instance",
         "Value":"nodes.k8s.terra10.nl"
      }
   ]
}

But what we really need to work with is an array containing only the instanceId of each instance hidden in the ResourceId section.

There are multiple ways to achieve this and most commonly in the git jungle out there we will encounter the immense popular .forEach() that does the job. But life can be simpler we will show.

So first an example using the .forEach():

// Using For-Each
const instanceIds: string[] = [];
result.Tags.forEach( instance => {
	instanceIds.push(instance.ResourceId!);
});
console.log('Array of instances with ForEach ' + instanceIds);

Notice how we first have to create an empty array and then loop over it ? That is 2 lines of code where we can do 50% better. 😉

Now let’s see how we can achieve the same result using .map():

// Build map of instanceId for request of instance details
const arrayOfResourceIds: string[] = result.Tags.map(tag => tag.ResourceId!);
console.log('Array of instances with Map ' + arrayOfResourceIds);

Voila!

Summary

So what does .map() do? Well it basically takes 2 arguments, a callback and an optional context (which was not used in the example). The callback runs for each item in the array and returns each value in the resulting array which means that the resulting array will always be the same length as the original one.

Also take note that often programming languages are based on identical concepts so you might encounter the same function there as well.

Hope it helps!