Tutorial

How To Use JavaScript Maps - .map()

Updated on March 19, 2024
author

William Imoh

English
How To Use JavaScript Maps - .map()

Introduction to Javascript Maps

From the classic for loop to the forEach() method, various techniques and methods are used to iterate through datasets in JavaScript. One of the most popular methods is the .map() method. .map() creates an array from calling a specific function on each item in the parent array. .map() is a non-mutating method that creates a new js array, as opposed to mutating methods, which only make changes to the calling array.

This method can have many uses when working with arrays. In this tutorial, you’ll look at four noteworthy uses of .map() in JavaScript: calling a function of array elements, converting strings to arrays, rendering lists in JavaScript libraries, and reformatting array objects.

Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Prerequisites

This tutorial does not require any coding, but if you are interested in following along with the examples, you can either use the Node.js REPL or browser developer tools.

How to Call a JS Function for each Item in an Array

.map() accepts a callback function as one of its arguments, and an important parameter of that function is the current value of the item being processed by the function. This is a required parameter. With this parameter, you can modify each item in an array and return it as a modified member of your new array.

Here’s an example:

const sweetArray = [2, 3, 4, 5, 35]
const sweeterArray = sweetArray.map(sweetItem => {
    return sweetItem * 2
})

console.log(sweeterArray)

This output is logged to the console:

Output
[ 4, 6, 8, 10, 70 ]

This can be simplified further to make it cleaner with:

// create a function to use
const makeSweeter = sweetItem => sweetItem * 2;

// we have an array
const sweetArray = [2, 3, 4, 5, 35];

// call the function we made. more readable
const sweeterArray = sweetArray.map(makeSweeter);

console.log(sweeterArray);

The same output is logged to the console:

Output
[ 4, 6, 8, 10, 70 ]

Having code like sweetArray.map(makeSweeter) makes your code a bit more readable.

How to Convert a JS String to an Array

.map() is known to belong to the array prototype. In this step you will use it to convert a string to an array. You are not developing the method to work for strings here. Rather, you will use the special .call() method.

Everything in JavaScript is an object, and methods are functions attached to these objects. .call() allows you to use the context of one object on another. Therefore, you would be copying the context of .map() in an array over to a string.

.call() can be passed arguments of the context to be used and parameters for the arguments of the original function.

Here’s an example:

const name = "Sammy"
const map = Array.prototype.map

const newName = map.call(name, eachLetter => {
    return `${eachLetter}a`
})

console.log(newName)

This output is logged to the console:

Output
[ "Sa", "aa", "ma", "ma", "ya" ]

Here, you used the context of .map() on a string and passed an argument of the function that .map() expects.

This works like the .split() method of a string, except that each individual string characters can be modified before being returned in an array.

How to Render Lists in JavaScript Libraries

JavaScript libraries like React use .map() to render items in a list. This requires JSX syntax, however, as the .map() method is wrapped in JSX syntax.

Here’s an example of a React component:

import React from "react";
import ReactDOM from "react-dom";

const names = ["whale", "squid", "turtle", "coral", "starfish"];

const NamesList = () => (
  <div>
    <ul>{names.map(name => <li key={name}> {name} </li>)}</ul>
  </div>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<NamesList />, rootElement);

This is a stateless component in React, which renders a div with a list. The individual list items are rendered using .map() to iterate over the names array. This component is rendered using ReactDOM on the DOM element with Id of root.

How to Reformat JavaScript Array Objects

.map() can be used to iterate through objects in an array and, in a similar fashion to traditional arrays, modify the content of each individual object and return a new array. This modification is done based on what is returned in the callback function.

Here’s an example:

const myUsers = [
    { name: 'shark', likes: 'ocean' },
    { name: 'turtle', likes: 'pond' },
    { name: 'otter', likes: 'fish biscuits' }
]

const usersByLikes = myUsers.map(item => {
    const container = {};

    container[item.name] = item.likes;
    container.age = item.name.length * 10;

    return container;
})

console.log(usersByLikes);

This output is logged to the console:

Output
[ {shark: "ocean", age: 50}, {turtle: "pond", age: 60}, {otter: "fish biscuits", age: 50} ]

Here, you modified each object in the array using the bracket and dot notation. This use case can be employed to process or condense received data before being saved or parsed on a front-end application.

JS Maps Conclusion

In this tutorial, we looked at four uses of the .map() method in JavaScript. In combination with other methods, the functionality of .map() can be extended. For more information, see our How To Use Array Methods in JavaScript: Iteration Methods article.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
William Imoh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

This infromation is relevant to the content if want to know more about our link

“With this parameter, you can modify each item in an array and create a new function.”

Shouldn’t this say “create a new array”? I don’t see how .map creates a “new function”.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more