Today yet another great array method, following reduce()
and filter()
, there is map()
.
What does map especially do well? It returns an array of specific values, let's say you only want a list of prices from your products?
Or a combined full name based on two fields?
Let me show you how map makes our lives easier for that.
Using the Javascript map() method
Let's start by creating an array of items.
const items = [
{ name: 'T-shirt plain', price: 9 },
{ name: 'T-shirt print', price: 20 },
{ name: 'Jeans', price: 30 },
{ name: 'Cap', price: 5 }
];
Now next we just want the prices really.
We could loop the items and push the price to a new array right?
let prices = [];
items.forEach(item => {
prices.push(item.price);
});
// [ 9, 20, 30, 5 ]
Success! But we needed to define an empty array and manually loop, it can just be made easier.
const prices = items.map(item => {
return item.price;
});
// [ 9, 20, 30, 5 ]
Ah cool! Same, but better.
As mentioned you can also use it to combine things let's say we have a list of users.
const users = [
{ firstname: 'Louise', lastname: 'Belcher' },
{ firstname: 'Bob', lastname: 'Belcher' },
{ firstname: 'Tina', lastname: 'Belcher' },
{ firstname: 'Jimmy', lastname: 'Pesto' }
];
Now we want to get the full names:
const fullnames = users.map(item => {
return `${item.firstname} ${item.lastname}`;
});
// [ 'Louise Belcher', 'Bob Belcher', 'Tina Belcher', 'Jimmy Pesto' ]
I hope you learned what cool things the map() method can bring, and give you an understanding of how to use it.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter