Using map() in Javascript

I'll teach you guys how to use the map() function on Javascript!

Hello guys, how’re you doing?

Hope you’re doing great!

In this post, I want to talk about the map() function, a function related to Arrays in Javascript that I use a lot and it’s very useful for various situations.

I’ll show you guys some real-life examples, hope you guys like it!

map()

The map() function is very useful when you need to translate or change the elements in an Array.

It loops through the Array from left to right, creating a new Array, and, for each item, it runs some function that you passed as args, and your function must return an value, so, this return will be the new item of the new Array.

Let’s see an example below.

Imagine that you receive this data from your API:

Simple data

So, you have an array of objects with:

- user id
- name
- location

Let’s figure out we don’t need all this data, we need only an array with objects like:

Example of what are we expecting

Problably, to resolve that, you may be thinking in something like:

Possible resolution

Right?

It isn’t wrong, and it’s works, but, there is a lot of steps, and, we can do it better!

Doing that way, you are:

1. Instancing a new variable;
2. Doing a for loop through the data Array, getting each index;
3. Using this index to access the current element of the Array;
4. Pushing the new object to the variable previously created;

The map() function provides an easy way to do exactly this and with less steps!

Check below how to write the same using map():

Refactor using map()

Maybe your reaction be like:

But, keep calm, i’ll explain every step!

When you execute Array.map(), to clear your mind in a real-life example, you can think in something like:

1. The map() gets your Array;
2. Loop through it, and, for each item it:
— Execute the function you’ve passed, passing the current item as an argument;
— Update the current item value, to the returned value from your function;

So, this also can be re-written to something like:

One more refactor

It will produce the same result and has the same effect.

And if you’re familiar with ES6, you can re-write it to:

The same code using ES6

But i’ll not talk about ES6 now, maybe in another post! :P

Using any of the examples above, if you run a console.log(newData), you will receive:

Result data

So, that’s it guys, as expected!!

You can see the JSFiddle of this post here.

I hope you guys understand about the map() function, but, if you have any questions please feel free to contact me!