Software, Tech & Coding simplified.

JavaScript map(): How to Transform Arrays [2022 Guide]

In JavaScript, you can use the Array.map() method to:

  1. Take an existing array
  2. Apply an operation for each element of the array
  3. Get a new array with modified elements

For instance, given an array of numbers, let’s create a new array of the numbers squared:

const numbers = [1, 2, 3, 4, 5]
const squared = numbers.map(num => num * num)

console.log(squared)

Output:

[1, 4, 9, 16, 25]

This returns a new array with the original numbers squared.

This is a comprehensive guide on how to use the map() method in JavaScript.

You are going to learn how to use the map() function instead of a for loop.

You will also learn what are callbacks, inline callbacks, and arrow functions.

All the theory is backed up with great examples.

If you are looking for other useful array methods, feel free to check this article.

Why Use the map() Method?

In JavaScript, you can use the map() method to make your code shorter and more concise.

The map() method lets you replace some lengthy for loops with good-looking shorthand statements.

Let’s make a comparison.

For Loop

In JavaScript, you can use a for loop to iterate over arrays.

Let’s see an example of using a for loop to transform an array of numbers into squared numbers.

To do this with a for loop, you need to:

  1. Create an empty array for storing the results.
  2. Start a for loop on the array of numbers.
  3. Square each number.
  4. Add the squared number to the result array.

Here is how it looks in code:

const numbers = [1, 2, 3, 4, 5]

let squared = []

for (const number of numbers) {
    squared.push(number * number)
}

console.log(squared)

Output:

[1, 4, 9, 16, 25]

The for loop gets the job done perfectly.

Also, this is something that is taught to beginners all the time.

However, this approach is more complex than it needs to be.

Instead of using a for loop, you can use the map() method to make the code shorter and more readable.

The map() Method

In JavaScript, you can use the map() method to transform one array into another.

The map() method works such that it calls a function for each element of the array. It then stores the results of the function calls into a new array.

Let’s repeat the previous example using the map() method.

To square an array of numbers using the map() method, you need to:

  1. Specify a function that squares a number.
  2. Call the map() method with the squaring function.

Here is how it looks in code:

const numbers = [1, 2, 3, 4, 5]
const squared = numbers.map(num => num * num)

console.log(squared)

As you can see, this looks way cleaner than the for-loop approach.

You now understand why the map() method is useful in JavaScript.

However, with this information, you cannot do much. Instead, you need to learn how the map() method works in detail.

It is time to take a deep dive into using the map() method in JavaScript.

The map() Method in JavaScript

In JavaScript, the Array.map() method calls a function for each element in an array.

The result is a new array with new transformed values.

Let’s start by looking at the syntax of the map() method.

The Syntax

There are many combinations of how to use the map() method.

You should choose an approach based on what you are trying to accomplish.

Here is a full list of all the possible syntaxes for calling the map() method:

// 1. Map with callback functions
map(callbackFn)
map(callbackFn, thisArg)

// 2. Map with inline callback functions
map(function(element) { /* action */ })
map(function(element, index) { /* action */ })
map(function(element, index, array){ /* action */ })
map(function(element, index, array) { /* action */ }, thisArg)

// 3. Map with arrow functions
map((element) => { /* action */ })
map((element, index) => { /* action */ })
map((element, index, array) => { /* action */ })

Let’s inspect the longest one of the approaches:

map(function(element, index, array) { /* action */ }, thisArg)

In this expression:

  • function is a callback that is called for each element in the array. The result is stored in a new array. The callback takes the following arguments:
    • element is the current array element we are operating on.
    • index is an optional parameter. It is the index of the current element being processed.
    • array is the array on which the map() method was called on.
  • this argument is optional. It specifies the value that is used as ‘this‘ when calling the callback on the array elements.

Most of the time you are only going to specify the element argument with nothing else.

So do not worry about the other arguments too much at this point.

I am going to show you an example of these towards the end of this guide.

Before seeing examples of the map() method, you need to learn what is a callback function.

Callbacks in JavaScript

In JavaScript, a callback function is a function passed as an argument to another function.

For instance, when you use the map() function, you pass it another function that is called for each element in the array.

The Array.map() Method with Callback Functions

The most basic way to use the map() method is by passing it a callback function.

For instance, let’s square an array of numbers.

const numbers = [1, 2, 3, 4, 5]

function square(number) {
    return number * number
}

const squared = numbers.map(square)

console.log(squared)

Output:

[1, 4, 9, 16, 25]

As you can see, the square function is defined separately. This function takes a number argument and returns a squared version of it.

You then pass this function as a callback to the map() method.

The reason why you do not need parenthesis is that the map() method only needs the name of the function. It knows how to handle the rest.

In other words, the map() method:

  • Takes whatever function name was passed to it.
  • Picks an element from an array.
  • Calls the function on the element.
  • Adds the result to a new array.

Now you understand how to use the map() method with a callback function.

But this is not your typical way of calling the map() method.

More often than not, you are going to use one of these:

  • An inline callback function.
  • An arrow function.

Let’s inspect both of these approaches starting from the inline callbacks.

The Array.map() Method with Inline Callback Functions

The word “inline” refers to a function used in the line of code where it is implemented.

In the previous example, you called the map() method with a callback function that was defined separately.

However, you can also define the callback inline when calling the map() method.

This means you implement the function without a name right in the map() method call.

For example, let’s square an array of numbers:

const numbers = [1, 2, 3, 4, 5]

const squared = numbers.map(function(number) {
    return number * number
})

console.log(squared)

Output:

[1, 4, 9, 16, 25]

As you can see, now there is no separate square function.

Instead, it is defined in the map() method call directly.

But why would you want to do this?

An inline callback is great when you only need the functionality once.

The above example demonstrates this well.

You only need the squaring functionality once. Thus it does not make sense to leave a useless function hanging in the codebase.

To make the inline callbacks even shorter, you can sometimes use arrow functions.

Let’s talk about arrow functions next.

The Array.map() Method with Arrow Functions

An arrow function is a shorthand alternative for a traditional function expression.

However, you cannot always use an arrow function.

To keep it short, I am not going to list the arrow function limitations here. Instead, you can check them here.

The arrow functions can be used with the following syntaxes:

param => expression

(param1, param2) => expression

param => {
    multiple_expressions
}

Compare these to the regular function syntax:

function name(param1, param2) {
    expressions
}

When it comes to using the map() method, you can benefit from using an arrow function as the callback.

For instance, let’s square an array of numbers using an arrow function:

const numbers = [1, 2, 3, 4, 5]
const squared = numbers.map(num => num * num)

console.log(squared)

Output:

[1, 4, 9, 16, 25]

As you can see, an arrow function like this makes the code even more readable.

Now you have seen the most common ways to use the map() method.

It is a great time to quickly learn how to use the other map() method arguments, that is:

  • index
  • array
  • thisArg

As already mentioned, these are not usually needed, but it is still worthwhile to understand how they work.

Examples with the Other map() Method Arguments

The map() method takes at most 4 arguments in total:

map(function(element, index, array) { /* action */ }, thisArg)

In the previous examples, you only saw examples with the element argument.

But sometimes you might need to be able to use the other arguments as well.

Let’s see two examples.

map(function(element, index, array))

When calling map(), you can make the callback accept the current array element.

In addition to this, you can also access the current element’s index and the array itself.

For instance, given an array of names that represents a queue in a shop your task is to:

  • Get the current position of each person in the queue.
  • Determine who comes after each person.
  • Add this information to a queueInfo object.

To do this, you need to access the current element, its index, and the array itself.

Here is how it looks in code:

const queue = ["Alice", "Bob", "Charlie"]

const queueInfo = queue.map(function(name, index, arr) {
    const next = index + 1 < arr.length ? arr[index + 1] : "No one"
    return {name: name, position: index + 1, next: next}
})

console.log(queueInfo)

Output:

[{
  name: "Alice",
  next: "Bob",
  position: 1
}, {
  name: "Bob",
  next: "Charlie",
  position: 2
}, {
  name: "Charlie",
  next: "No one",
  position: 3
}]

Next, let’s see how to override this in the map() method’s callback.

map(callback, thisArg)

In addition to the callback function, the map() method takes a second parameter, thisArg.

This argument lets you override this within the scope of the callback function.

This is useful if you want to reuse the callback in different contexts.

For instance, given an array of x,y coordinates let’s transform them according to the screen size of the current view:

let posData = [[50, 100], [200, 300]]
const defaultSize = { width: 320, height: 480 }

function transform(coords) {
    return [
  	coords[0] * this.width / defaultSize.width,
        coords[1] * this.height / defaultSize.height,
    ]
}

let newPosData = posData.map(transform, { width: 1280, height: 1920 })

console.log(newPosData)

Output:

[[200, 400], [800, 1200]]

Here we specified the current screen size as the thisArg in the map() method.

If you change a view again, all you need to do is specify the new view to the callback by overriding this in the map() method call.

Example Use Cases for the map() Method

Last but not least, let’s take a look at some examples of how to use the map() method.

Example 1: Call a Function for Each Element in an Array

You can use the map() method to transform one array into another by calling a function for each element in the array.

For instance, given an array of strings, let’s create a new array with the strings in the upper case.

const names = ["Alice", "Bob", "Charlie"]

const capsNames = names.map(name => name.toUpperCase())

console.log(capsNames)

Output:

["ALICE", "BOB", "CHARLIE"]

Example 2: Reformat Array Objects

The map() method can be used when working with arrays of objects as well.

For example, given an array of user objects, let’s transform the string values to uppercase:

const users = [
    { name: 'Bob',     hobby: 'Jogging' },
    { name: 'Charlie', hobby: 'Gym' },
    { name: 'Alice',   hobby: 'Golf' }
]

const capsData = users.map(user => {
    const userData = {}

    userData.name = user.name.toUpperCase()
    userData.hobby = user.hobby.toUpperCase()

    return userData
})

console.log(capsData)

Output:

[{
  hobby: "JOGGING",
  name: "BOB"
}, {
  hobby: "GYM",
  name: "CHARLIE"
}, {
  hobby: "GOLF",
  name: "ALICE"
}]

This creates a new array with new objects with the desired transformation applied to them.

Example 3: Convert a String to an Array of Characters

This is a bonus example.

The map() method is known to belong to the Array data type.

However, you can extract this method from the Array and use it on a string.

To do this, use the .call() method.

The .call() method lets you use the context of one object for another. In this case, you can use the map() method that belongs to an Array on a String.

For instance, let’s convert a string to an array of upper case characters.

const name = "Sam"

const arr = Array.prototype.map.call(name, letter => letter.toUpperCase())

console.log(arr)

Output:

["S", "A", "M"]

Conclusion

Today you learned how to use the map() method in JavaScript.

To recap, the map() method can be used to transform one array into another.

The map() method does not modify the original array. Instead, it creates a new one.

The map method works by calling a callback function on each array element. This function returns a new value that is added to the new transformed array.

Thanks for reading.

Happy coding!

Further Reading

JavaScript Interview Questions

JavaScript forEach() Method

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email