Introduction
Hi there my friend, I was writing a bit of code today and I noticed I was using the .map method more often than normal, so much it started to feel like a sign... A sign to save someone else from the confusion I had the first time I used it.
First, let's talk about the Array.map() method and after that, we'll visualize it.
What is the Array.map() method?
If you tried the project from the first article. You'll notice we went through the array using the for. loop. Well, the Array.map() method does the same thing and goes one step further, it iterates over an array(iterating over an array means going over the array, one item at a time) and allows you to call a function on each member of the array. After doing this, it copies the results into a new array without modifying the original array.
You might wonder how useful this is to you. The truth is, at some point in your developer journey, you'll work with data from APIs and that data could continuously change. The Array.map() method allows you to work on that data easily.
If you didn't understand everything I said up there, that's fine, you'll see what it means as you go on.
Now it's time to visualize the Array.map() method and to do this We'll build a collection of product description cards for a business.
Setting up our editor
Our first step is to get our code editor open and ready for action. Open up your code editor and create your HTML, CSS and JS files.
Create the basic markup for your HTML and don't forget to link your CSS and JS files to your HTML now to avoid headaches later.
Creating a placeholder
Start up your liveserver so you can see what we're making on your browser as you work on it.
Now let's create a placeholder card in our HTML.
<section class = "section-center">
<article>
<img src="https://unsplash.com/photos/kPxsqUGneXQ" alt="">
<div class="item-info">
<header>
<h4 class="item">buttermilk pancakes</h4>
<h4 class="item-price">$15</h4>
</header>
<p class="item-desc">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Reprehenderit at tenetur deleniti assumenda repudiandae explicabo accusamus! Atque pariatur ratione eaque.</p>
<button>Get one</button>
</div>
</article>
</section>
Feel free to use whatever image you want for the placeholder image source, but if you're short of options, feel free to follow the URL in the image source to get royalty-free images for free.
Styling our card
Now that we've created our card's structure, it needs some styling and to do this I have written some CSS below.
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,500;1,200&display=swap');
*{
margin: 0;
padding: 0;
text-decoration: none;
font-family: Poppins;
}
button{
cursor: pointer;
background-color: red;
color: white;
height: 30px;
width: 80px;
border: none;
padding: 5px;
}
section{
padding: 2em;
display: flex;
justify-content: center;
gap: 10px;
flex-wrap: wrap;
}
article{
display: flex;
flex-direction: column;
width: 15em;
box-shadow: 5px 5px 10px 0.1px grey;
margin-bottom: 10px;
}
img{
background-size: cover;
max-width: 100%;
}
.item-info{
padding: .5em;
display: flex;
flex-direction: column;
gap: 10px;
}
Adding the CSS gives us the image below.
We now have a single card on our screen acting as a placeholder
Your card image likely looks different since we're using different images, but the card structure should be the same.
If you feel the need to spice the CSS up even more to suit your taste then go for it.
Alright, we've created our card. Now let's move on to JavaScript where we'll use the Array.map() method
Mapping over our Array
I'll drop some JS code for you to type into your editor and I'll give a breakdown of it.
Go to your JS file and type the code below into it
const menu = [
{
id: 1,
title: "Triple layer Cake",
price: "$15.99",
img: "https://unsplash.com/photos/kPxsqUGneXQ",
desc: `I'm baby woke mlkshk wolf bitters live-edge blue bottle, hammock freegan copper mug `,
btn: "I want this"
},
{
id: 2,
title: "Vanilla goodness",
price: "$13.99",
img: "https://unsplash.com/photos/vdx5hPQhXFk",
desc: `vaporware iPhone mumblecore selvage raw denim slow-carb leggings gochujang helvetica`,
btn: "I want this"
},
{
id: 3,
title: "Chocolate cupcake",
price: "$6.99",
img: "https://unsplash.com/photos/6SHd7Q-l1UQ",
desc: `ombucha chillwave fanny pack 3 wolf moon street art photo booth before they sold out organic viral.`,
btn: "I want this"
}]
const section = document.querySelector('.section-center')
function displayMenuItems(){
let displayMenu = menu.map(function(item){
return `
<article>
<img src=${item.img} alt="">
<div class="item-info">
<div class="item-div">
<h2 class="item">${item.title}</h2>
<h4 class="item-price">${item.price}</h4>
</div>
<p class="item-desc">${item.desc}</p>
<button class>${item.btn}</button>
</div>
</article>
`
})
section.innerHTML = displayMenu
}
displayMenuItems()
This might look long and intimidating. I promise it's not, if you look closely you'll see that there are only a couple of things that might be new to you - the main one being the Array.map() method.
Let's start by breaking the code into understandable chunks.
First, we created an Array named menu and in that array, we have some objects. This might be your first time seeing objects in arrays, but you'll get used to it as you keep working with JavaScript.
Our objects have some individual properties that we will reference later: title, desc etc.
After creating our array of objects, we move on to the next line where we declare a variable called section
const section = document.querySelector('.section-center')
This references the HTML tag with the class name "section-center". This allows us to do some DOM manipulation of that section later.
Next, we write a function called 'displayMenuItems'.
function displayMenuItems(){
let displayMenu = menu.map...
}
Inside that function block, we created a new array called 'displayMenu' and immediately assigned it the results of our menu.map method. Recall that the Array.map() method takes an array iterates over it and gives you results in a new array.
In our example, our original array is named 'menu' and the new array modified by array.map is our variable named 'displayMenu'.
What 'menu.map' does is go over the array named 'menu' and execute the code in the function block on each member of the array.
In the code below our .map method takes a parameter called 'item', this is the name we give the objects in our array. You can call it anything you want.
function displayMenuItems(){
let displayMenu = menu.map(function(item){
...
})
}
Next, we have a return keyword and a code block that may look surprising to you since it looks like HTML.
return
`
<article>
<img src=${item.img} alt="">
<div class="item-info">
<div class="item-div">
<h2 class="item">${item.title}</h2>
<h4 class="item-price">${item.price}</h4>
</div>
<p class="item-desc">${item.desc}</p>
<button class>${item.btn}</button>
</div>
</article>
`
What we have here is indeed the exact markup in our HTML. If you noticed while we were writing our HTML, I said we were creating a placeholder card, what we created is the default card to load before our JavaScript comes up.
You may also notice the use of template literals(${}) in our code. This is used to access the object's property. You can read more on template literals on MDN docs
Our next step is to append our displayMenu array to our HTML section using the code below. This is basically DOM manipulation
section.innerHTML = displayMenu
Finally, we invoke our function outside the function block
displayMenuItems()
After all this, we get three cards as shown in the image below.
If your screen comes up blank or shows no change, please look through your code for any errors or omissions.
Of course, this is just the tip of the iceberg when it comes to the number of things you can do with the Array.map() method.
If you want to do some more research, You can read more on the Array.map() method.
Conclusion
We've seen how to use the map method to go through an array of objects, pick each object in that array and return some properties of those objects. We then structured those objects using HTML.
When you start working with APIs you'll appreciate the Array.map() method even more because you could get data of objects ranging into hundreds and you could use all!
In the next article of this series, we'll talk about the filter method, another popular JavaScript method you'd do well to learn.
If you have any questions, comments or suggestions for this article or any other thing please feel free to drop them below or reach out to me on Twitter where I'm usually more active.