How to Use Javascript’s Array map Method
Tags: javascript, beginners
Published: 2019-06-08 12:36:27

---
title: How to Use Javascript’s Array map Method
description: Javascript's array map method lets you make a copy of an array, but with each value tweaked by a callback function you provide. I'll teach you how it works and let you play with a demo app.
published: true
tags: javascript, beginners
canonical_url: https://raddevon.com/articles/how-to-use-javascripts-array-map-method/
cover_image: https://raddevon.com/wp-content/uploads/2019/05/sound-wave-tapes-transform.gif
---
What It Does
------------

Javascript’s array `map` method returns a transformed array. You pass it a function that will transform each value in the array. Map will call your function with each item in the array, passing three values: **the array item, the index of that item, and the entire array**. Whatever your function returns will become the corresponding item in the new array.

An Example
----------

The best way to understand what map does is through an example. Here’s a function that will transform a title with a leading article (“a,” “an,” or “the”). It returns the same title with the article moved to the end. If you have a list of titles and want to alphabetize them, you want to make sure those leading articles don’t influence the order. You wouldn’t want all the titles starting with “The” sorted with the ‘t’s.

```javascript
    function formatTitle(title) {
      const articles = ['a', 'an', 'the'];
      let titleWords = title.split(' ');
      let firstWord = titleWords.shift();
      if (articles.includes(firstWord.toLowerCase())) {
        let formattedTitle = `${titleWords.join(' ')}, ${firstWord}`;
        return formattedTitle;
      } else {
        return title;
      }
    }
```

### Breaking Down the Callback Function

Let’s break this function down. The function takes one argument: **a title**. I know map will pass two more arguments besides the title, but I won’t need those. I only need to name parameters I’m actually going to use in my function. The others will still be passed but won’t have parameter names associated with them.

On line 2, I’ve created an array of the articles that I’ll look for. Later, I’m going to take the first word of the title and **see if it appears in this array**. That tells me if this title needs to be formatted or not.

Line 3 takes the title and calls the `split` method passing in a space. `split` is a string method that breaks a string into an array. The string you pass to `split` is the string the original string gets split on. This one will get split apart at each space character into an array of the words in the string.

Line 4 uses `shift` which removes the first value from the array _and_ returns it. That first word is now stored in the `firstWord` variable, and the `titleWords` array no longer contains the first word.

On Line 5, I test to see if the `articles` array contains a lower-case version of `firstWord` by passing that to the includes method. Every title should start with an uppercase letter, but, by lower-casing the word before comparing, I don’t have to worry if the user of this application is actually doing the right thing and capitalizing their title. The function will just work regardless.

If the first word was found in the `articles` array, I’m going to build the formatted string. I’m doing this with a template string that starts by re-joining the remaining words in the title using the array’s `join` method. Passing a string with nothing but a space means that’s what will be placed between the strings in the array when they’re re-joined. Remember, this array doesn’t contain the first word, which we’ve now determined is an article.

I place a comma after that followed by the first word. Then, I drop in the leading article (`firstWord`) at the end and return that value. If the first word _wasn’t_ an article (the else case), I just return the original title instead.

_Learning to write code is great, but you probably want to move beyond just learning and actually **get paid to write code**. I can help you take that leap. Sign up at [Rad Devon](https://raddevon.com/) to get help starting your web development career!_

### Calling Map

To use that callback, I’ll call `map` on the original array and pass in the `formatTitle` function. This will return a transformed array with formatted titles instead of the originals. Since it’s returning a new array instead of changing the original array, I’ll probably want to capture it with a variable assignment or pass it straight into another function or method. Here’s what everything looks like assembled into a working application.

A Working Demo
--------------

This demo uses the exact callback function shown above. It’s a simple Vue app that displays the top 10 movies on IMDB, sorted alphabetically. In the first list, they’re sorted by title without any modification. In the second list, I’m sorting a new array generated by passing `formatTitle` into map.

{% codepen https://codepen.io/raddevon/pen/gJKqqe/ default-tab=js,result %}

When to Use Map
---------------

Maybe you need to format a string in a particular way like the demo above or maybe you need to perform a calculation on each value in an array of numbers. In either case, `map` is the best tool for the job. Use `map` any time you need a new array in which **each value is a transformation of a value in an existing array**.

_If you like this article, you might also enjoy my articles on [learning to use the Javascript ternary operator](https://raddevon.com/articles/javascripts-ternary-operator-a-compact-alternative-to-if-else/) and [the array’s reduce method](https://raddevon.com/articles/how-to-use-javascripts-array-reduce-method/)._