Hello guys, how’re you doing?
Hope you’re doing great!
I’ll show you guys some real-life examples, hope you guys like it!
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:
So, you have an array of objects with:
- user id
Let’s figure out we don’t need all this data, we need only an array with objects like:
Problably, to resolve that, you may be thinking in something like:
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():
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:
It will produce the same result and has the same effect.
And if you’re familiar with ES6, you can re-write it to:
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:
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!