Map
Objectives
Implement a
map()
function from scratch.
Introduction
In the previous lesson, we learned about .filter()
, a built-in array method that searches through a collection, passes each element to a provided callback function, and returns an entirely new array comprised of elements for which the callback returned a truthy value.
Another very common built-in array method is .map()
, which transforms every element in an array to another value. For example, it can be used to square every value in an array of numbers: [1, 2, 3]
-> [1, 4, 9]
. Map also accepts a callback function, and it passes each element successively to the callback:
Let's quickly run through how we could create our own version of the .map()
method.
Abstracting the iteration
Right off the bat, we know that our function needs to accept the array from which we'd like to map values as an argument:
Inside the function, we need to iterate over each element in the passed-in array, so let's fall back on our trusty for...of
statement:
Callback city
We want to transform values from the array, but for code organization and re-usability it's best to keep that logic decoupled from the map()
function. map()
should really only be concerned with iterating over the collection and passing each element to a callback that will handle the transformations. Let's accept that callback function as the second argument to map()
:
And inside our iteration, we'll want to invoke the callback, passing in the elements from array
:
Let's make sure this is working so far:
Returning a brand new collection
Logging each squared number out to the console is fun, but map()
should really be returning an entirely new array containing all of the squared values. Show off that new collection!
Fierce.
First, let's create that new array:
Inside the for...of
statement, let's .push()
the return value of each callback invocation into newArr
:
And at the end of our map()
function we're going to want to return the new array:
Let's test it out!
Flatbook's expanding engineering team
Let's use our map()
function on a trickier data structure — a list of recently onboarded engineers. First off, we need to flip each new engineer's account from a normal user to an admin:
Notice that we're using Object.assign()
to create a new object with updated values instead of mutating the original object's accessLevel
property. Nondestructive updating is an important concept to practice — destructively modifying objects at multiple points within a code base is one of the biggest sources of bugs.
Next, we just need a simple array of the new engineers' userID
s that we can shoot over to the system administrator:
Finally, let's use the built-in Array.prototype.map()
method to indicate that all the new engineers have been provided a new work laptop:
Now that we understand how the built-in .map()
array method is implemented, we can stick to the native method and get rid of our copycat map()
function.
Resources
Last updated