2.6: map
If you don't know the .map() method already, you need to know it. If you already know what it does, it doesn't hurt to practice it.
Let's add our data to the file, just an array of instructor objects, that includes their name and special skills:
Let's say that we want to iterate over this array and print just the names of the instructors. We'll use a for loop:
What do we have to do here: 1. Manage the index. 2. Check the length. 3. Increment. 4. Create an empty array. 5. Etc.
We have to create an empty array to push the names into as we iterate through. This approach is fine for learning programming, but with ES5, the .map() function came along to make things more sleek for common tasks like iterating through a collection.
Here it is:
Notice a few things here: 1. We create a variable called instructorNames that store the result as an array of objects. 2. We are calling .map on the instructors array: instructors.map
. 3. The instructor
parameter in .map can be named anything, usually something related to the array. See how this is the exact same thing:
The .map() function requires a return value. This is a key rule of using .map(), so the fat arrow is taking care of that requirement.
Get some practice. Try the following. Fix the code:
.map() and React
Last updated