Create your own
Lesson illustration

Transforming Arrays with Map

Hello! Welcome to your next lesson on modern JavaScript.

Introduction

In our last lesson, we explored arrow functions and saw how their concise syntax makes them perfect for callbacks. We even had a small preview of how they work with array methods. Today, we're going to dive deep into one of the most important array methods in JavaScript: map.

This lesson addresses the learning outcome: Create new arrays by transforming data using the map method.

The map method is a cornerstone of modern JavaScript for data manipulation. As a designer, you often work with lists of items in your UIs—a list of user profiles, products in a catalog, or navigation links. The map method is the primary tool developers use to take raw data (like from a database or an API) and transform it into the structured elements needed to build these lists.

In this lesson, we will cover:

  • What the map method does and why it's preferable to older loop-based approaches.
  • How to use map with arrow functions to transform arrays of simple values (like numbers or strings).
  • How to transform arrays of objects to extract data or create new, restructured objects.
  • The common pattern of using map to generate HTML content from a data array.

1. What is map? From Iteration to Transformation

At its core, the map method is a way to create a new array by applying a function to every single element of an existing array.

Imagine you have an array [1, 2, 3]. If you map over it with a function that doubles each number, you get a new array [2, 4, 6]. The original array [1, 2, 3] remains unchanged. This principle is called immutability, and it's a key concept in writing predictable and maintainable code.

Before map, you would have to create an empty array and use a for loop to manually push transformed items into it. The map method automates this entire process, making your code cleaner and more declarative.

Let's watch a video that introduces map and contrasts it with other methods like forEach.

How to use map() filter() reduce() | JavaScript Array Methods Tutorial

This video from the Coding2GO channel provides a great introduction to the map method. It clearly explains the core concept of creating a new, transformed array without modifying the original.

Watch from the beginning to 02:02. Pay close attention to the comparison between using a forEach loop and using the map method to achieve the same result. Notice how map is more efficient and direct.


2. The Syntax of map

As you saw in the video, map takes a callback function as its argument. This callback function is executed for each element in the array. Whatever the callback function returns becomes the element in the new array at the same position.

This image shows a simple example of using `map` to multiply each element in an array by 3, resulting in a new, transformed array.

Let's look at the official syntax and definition from the MDN Web Docs, which is the definitive resource for JavaScript.

Array.prototype.map() - JavaScript - MDN Web Docs

The MDN Web Docs for Array.prototype.map() provides the formal definition and syntax. It's always good practice to consult the official documentation.

Read the introduction, the 'Try it' example, and the 'Syntax' section. Focus on understanding the three arguments passed to the callback function: element, index, and array.

To summarize the syntax, especially when combined with the arrow functions you learned in the last lesson:

const numbers = [1, 4, 9, 16];

// The callback receives the element, its index, and the original array
const roots = numbers.map((element, index, array) => {
  console.log(`Processing element ${element} at index ${index}`);
  return Math.sqrt(element);
});

// In most cases, you only need the element
const doubles = numbers.map(num => num * 2);

console.log(doubles); // [2, 8, 18, 32]

If your callback doesn't return a value (or returns undefined), the new array will be filled with undefined values. This is a common mistake, so always remember to include a return statement if you're using a block body {}.


3. Common map Transformations

The real power of map comes from its versatility. You can transform data into anything you need. Let's explore a few practical examples.

3.1. Transforming Data into HTML

A very common task in front-end development is rendering a list of items from a data array. map is perfect for this. You can transform an array of data into an array of HTML strings.

JavaScript Array Map

This video from Programming with Mosh demonstrates exactly how to map an array of numbers into an array of HTML list item (<li>) strings.

Watch from 00:17 to 02:49. Notice how he first creates an array of strings and then uses the join('') method to combine them into a single HTML block. This is a very common and powerful pattern.

Here's the core idea from the video:

const productNames = ['Figma', 'Sketch', 'Adobe XD'];

// Map the array of names to an array of <li> strings
const listItems = productNames.map(name => `<li>${name}</li>`);
// listItems is now: ['<li>Figma</li>', '<li>Sketch</li>', '<li>Adobe XD</li>']

// Join the array into a single string to inject into the DOM
const html = `<ul>${listItems.join('')}</ul>`;
// html is now: '<ul><li>Figma</li><li>Sketch</li><li>Adobe XD</li></ul>'

// You would then set this as the innerHTML of an element
// document.body.innerHTML = html;

3.2. Transforming Data into Objects

You can also transform a simple array into a more complex array of objects. This is useful for adding structure to your data.

In the last lesson, we noted that returning an object from a concise arrow function requires wrapping the object in parentheses (). Let's see a video that reinforces this concept in the context of map.

JavaScript Array Map

Let's continue with the Programming with Mosh video. He provides a clear explanation of mapping numbers to objects and highlights the specific syntax required for arrow functions.

Watch from 02:49 to 05:22. Pay close attention to the part where he explains why n => { value: n } doesn't work and how to fix it with n => ({ value: n }).

3.3. Transforming an Array of Objects

This is perhaps the most frequent use case for map. You'll often receive an array of objects from an API and need to either extract specific pieces of information or reformat the objects for your UI.

Let's watch a final video that demonstrates how to handle this.

How to use map() filter() reduce() | JavaScript Array Methods Tutorial

The Coding2GO video has an excellent segment on working with arrays of objects. It shows how to update a property while keeping the others, and how to extract just one property.

Watch from 03:10 to 04:35. Focus on the use of the spread operator (...product) to create a new object that copies the old properties while overriding the price. This is a fundamental pattern for immutably updating objects.

Here are the two key patterns from the video:

  1. Extracting a single property:

    const users = [
      { id: 1, name: 'Alex' },
      { id: 2, name: 'Jordan' },
    ];
    const userNames = users.map(user => user.name);
    // userNames is now: ['Alex', 'Jordan']
    
  2. Creating new, modified objects:

    const products = [
      { name: 'Laptop', price: 1200 },
      { name: 'Mouse', price: 25 },
    ];
    const productsWithTax = products.map(product => ({
      ...product, // Copy all original properties
      priceWithTax: product.price * 1.2, // Add a new property
    }));
    /*
    productsWithTax is now:
    [
      { name: 'Laptop', price: 1200, priceWithTax: 1440 },
      { name: 'Mouse', price: 25, priceWithTax: 30 }
    ]
    */
    

4. Practice Exercise

Time to put this into practice. Below is a script with an array of designAssets. Each asset has a name and a priceInCents.

Your Goal:
Use the map method to create a new array called formattedAssets. Each object in the new array should have the same name, but also include a new price property that is a formatted string (e.g., $15.00).

Hint: To convert cents to dollars, divide by 100. You can use the toFixed(2) method on a number to format it to two decimal places (e.g., (1500 / 100).toFixed(2) would result in "15.00").

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Map Practice</title>
</head>
<body>
    <h1>Design Assets</h1>
    <div id="output"></div>

    <script>
        const designAssets = [
            { name: 'Icon Pack', priceInCents: 1500 },
            { name: 'UI Kit', priceInCents: 4999 },
            { name: 'Font License', priceInCents: 2500 },
            { name: 'Mockup Template', priceInCents: 950 }
        ];

        let formattedAssets;

        // --- YOUR CODE HERE ---
        // Use the .map() method on `designAssets` to create the `formattedAssets` array.
        // Each new object should look like: { name: '...', price: '$XX.XX' }
        
        
        
        // --- END OF YOUR CODE ---

        console.log(formattedAssets);
        // Expected output in console:
        // [
        //   { name: 'Icon Pack', price: '$15.00' },
        //   { name: 'UI Kit', price: '$49.99' },
        //   { name: 'Font License', price: '$25.00' },
        //   { name: 'Mockup Template', price: '$9.50' }
        // ]

        // This code will display the result on the page
        document.getElementById('output').innerHTML = `
            <pre>${JSON.stringify(formattedAssets, null, 2)}</pre>
        `;
    </script>
</body>
</html>
Click here for the solution
formattedAssets = designAssets.map(asset => {
    const priceInDollars = (asset.priceInCents / 100).toFixed(2);
    return {
        name: asset.name,
        price: `$${priceInDollars}`
    };
});

// Or as a more concise one-liner:
formattedAssets = designAssets.map(asset => ({
    name: asset.name,
    price: `$${(asset.priceInCents / 100).toFixed(2)}`
}));

Both solutions are correct. The second one is more compact and is a style you will see often in professional codebases.


Conclusion

Excellent work! You've now mastered the map method, a fundamental tool for any front-end developer. Combining map with arrow functions allows you to write clean, expressive, and powerful code for transforming data.

Key Takeaways:

  • Transformation, Not Mutation: map creates a new array and leaves the original array untouched.
  • Return is Key: The value returned by the callback function determines the content of the new array.
  • Versatile: You can transform data into different types, from simple numbers to strings of HTML to entirely new object structures.
  • UI Powerhouse: map is the standard way to turn arrays of data into lists of elements in a user interface.

In our next lesson, we'll look at a close cousin of map: the filter method. While map transforms every element in an array, filter allows you to create a new array containing only the elements that meet a certain condition. They are often used together to first select, then transform data.

Can't find a good explanation? Sign up and we'll make it for you

Sign up