How to Use the map Method in JavaScript
Transforming every item in an array with the map method.
There are times when you have an array of data and need a new array where every
item has been changed in some way, like doubling a list of numbers or pulling
the names out of a list of users. Instead of writing a for loop and pushing
into a new array, you can use the map method.
The map() method creates a new array with the result of calling your
function on every item in the original array.
How map Works
map calls your callback once for every item in the array. Whatever you return
from the callback becomes the item at the same position in the new array:
const result = arr.map((element, index, array) => {// return the new value for this element})
The callback gets three arguments:
elementis the current itemindexis the position of the current itemarrayis the original arraymapwas called on
The new array always has the same length as the original.
Mapping Numbers
Here's a basic example that doubles every number:
const numbers = [1, 2, 3, 4]const doubled = numbers.map((number) => number * 2)console.log(doubled) // [2, 4, 6, 8]console.log(numbers) // [1, 2, 3, 4]
The original numbers array is left alone. map always gives you back a new
array.
Mapping an Array of Objects
This is where map really comes in handy. Say you get a list of users back from
an API and only need their names:
const users = [{ id: 1, firstName: "Jim", lastName: "Halpert" },{ id: 2, firstName: "Pam", lastName: "Beesly" },]const names = users.map((user) => `${user.firstName} ${user.lastName}`)console.log(names) // ["Jim Halpert", "Pam Beesly"]
You can also return a new object for each item. Wrap the object in parentheses so JavaScript doesn't read the curly braces as the function body:
const options = users.map((user) => ({value: user.id,label: user.firstName,}))// [{ value: 1, label: "Jim" }, { value: 2, label: "Pam" }]
Using the index
The second argument is the index, which is handy for numbering a list:
const steps = ["Install", "Configure", "Deploy"]const numbered = steps.map((step, index) => `${index + 1}. ${step}`)// ["1. Install", "2. Configure", "3. Deploy"]
Don't Forget to Return
The most common map mistake is forgetting to return a value. When you use
curly braces in an arrow function you need an explicit return, otherwise every
item ends up undefined:
const broken = numbers.map((number) => {number * 2})// [undefined, undefined, undefined, undefined]const fixed = numbers.map((number) => {return number * 2})// [2, 4, 6, 8]
Note: If you don't need the new array and only want to run some code for each
item, use forEach instead.
You'll end up using map a lot, especially for rendering lists of data.
Have some feedback on this post? .