The Map Array Method In JavaScript

The Map Array Method In JavaScript

ยท

4 min read

Introduction

One of the most important aspect of Web Development is rendering data dynamically to the browser.

The map array method helps us do that but it can get confusing even after frequently using it.

In this article, you will learn how to use the JavaScript map method.

Map method in JavaScript

The map method is one of the most useful array methods in JavaScript. If you don't know about methods, you can read about it here.

The map method is called on an existing array and it creates a new array by returning a new array.

Here's a brief example.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="demo"></div>

    <script src="script.js"></script>
</body>
</html>
// script.js

const numbers = [4, 9, 16, 25];
document.getElementById("demo").innerHTML = numbers.map(function (num) {
  return Math.sqrt(num);
});

Result

The numbers is an array of four different numbers.

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

document.getElementById("demo").innerHTML will select an HTML element with an id of demo.

The element is set to the result of numbers.map(function(num) {return Math.sqrt(num)}) .

The map() method is called on numbers array by attaching the .map() . The map method takes a callback function in .map(callback function), which is function(num) {return Math.sqrt(num)}.

A callback function is a function that is an argument of a function. I wrote a blog about callback functions, click here to read more.

The callback function takes in a parameter called num . num represents each item in numbers array which is 4, 9, 16 and 25. The callback function is called or run on every item in the numbers array.

The callback function is also returning Math.sqrt(num) for each item. Math.sqrt(x) is a function to get the square root of x. Therefore, the callback function will get the square root of all the numbers in the numbers array.

Note that .map() method does not change the original array it is attached to.

Map method on Array of Objects

Consider the .map() on an array of objects.

// person is an array containing firstName and lastName in each object.

const person = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Frank", lastName: "Mikel" },
  { firstName: "Mark", lastName: "Joe" },
];

In the code above, there is an array called person which contains 3 objects {..} having 2 properties each firstName and lastName .

You can call the map method on person and attach a callback function as argument.

In the previous example, we only had num as the only parameter, but in this example, we will have more than one parameters.

Callback Functions Parameters

The two most popular parameters that the map callback function can take are:

  1. item: can be called any name, it is a representation of each item in the initial array (person, numbers).

  2. index: can be called any name, it represents the number of each item in array starting from 0.

Other parameter that can be passed is the array of the current element which is rarely used.

Here's how you can use the map() method on the person array.

const personNamesElement = person.map(
  function (eachPerson, index) {
    return "<p>Number " + (index + 1) + ": " + eachPerson.firstName + " " + eachPerson.lastName + "</p>"
  });

eachPerson represents each object in the person array while index represents the number of each object starting from zero (0).

This is the new array returned to personNamesElement below.

['<p>Number 1: John Doe</p>',
 '<p>Number 2: Frank Mikel</p>',
 '<p>Number 3: Mark Joe</p>']

To make the <p> elements show in your browser, you need to join the elements and display it to the HTML body.

document.getElementById("demo").innerHTML = personNamesElement.join("");

Here's the whole HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="demo"></div>

    <script src="script.js"></script>
  </body>
</html>

Here's the whole JavaScript:

const person = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Frank", lastName: "Mikel" },
  { firstName: "Mark", lastName: "Joe" },
];

const personNamesElement = person.map(function (eachPerson, index) {
  return (
    "<p>Number " + (index + 1) + ": " + eachPerson.firstName + " " + 
     eachPerson.lastName + "</p>"
  );
});

document.getElementById("demo").innerHTML = personNamesElement.join("");

Here's the result in the browser:

Conclusion

The map() method in JavaScript is used to iterate over an array and transform each element of the array based on a provided callback function.

The map() method does not change the original array, it returns a new array containing the results of applying the callback function to each element of the original array.

That will be all. Hope you found value here as you learn to build more projects effectively.

If you enjoyed this article and want to see more content related to JavaScript and Web development, then follow me here, Twitter (X) or connect on LinkedIn. I'd be happy to count you as one of my ever-growing group of awesome friends on the internet.

You can also join my WhatsApp developer community and OpenSource community of 330+ developers learning and building cool projects.

If you also want to support me, you can buy a cup of coffee for me here.

Thanks && Bye. ๐Ÿ‘‹