Tip 22: Create Arrays of a Similar Size with map()

In this tip, you’ll learn how to pull out a subset of information from an array using map().

In the previous tip, you saw how you could rewrite a simple for loop with an array method. Now you’re going to start exploring how to use specific array methods.

Using map()

You’ll begin with map() (not to be confused with the Map object). It’s fairly common, and your new array receives the information you return in a brand new array. In other words, the return value is transparent, which isn’t the case with other array methods. Here’s another good reason to start with map(): the name “map” isn’t very expressive. What does that even mean? When I first learned it, I needed a fair amount of experience before I could see and understand a map function at a glance.

Your goal is to get an idea of how most array methods work. And your secondary goal is to gain enough experience with map() that you’ll start to see why it’s one of the most popular methods.

Example

Start with a simple map function. A map function takes a piece of information from an input array and returns something new. Sometimes it returns part of the information. Other times, it transforms the information and returns the new value. That means it can take a single property from an array, or it can take a value in an array and return an altered version. For example, it can return an array with all the values capitalized or converted from integers to currency.

The easiest example is pulling specific information from an object. Let’s start with a collection of musicians.

Get hands-on with 1000+ tech skills courses.