Member-only story
Map
This function returns a new array with a callback function acting upon every element within the array. Map will run a callback function that takes 3 arguments. The first being the “current item” in the array (this is a required argument), the second being the “index” within the array of the current item (this is an optional argument), finally, the last argument in the callback is the entire array itself (this is also an optional argument).
Here is an example of an array of objects I have created which contains a few of my favourite movies (Don’t judge me!), each with their movie name and the name of the actresses/actors who starred in them.
var favouriteMovies = [
{'name':'aliens','mainStar':'Sigourney Weaver'},
{'name':'Predator','mainStar':'Arnold Schwarzenneger'},
{'name':'Godzilla','mainStar':'Bryan Cranston'},
{'name':'Blade','mainStar':'Wesley Snipes'},
{'name':'Prometheus','mainStar':'Noomi Rapace'}
]
For this example I will just be extracting the movie name from the object of arrays using map and to do this is seen below.
var movieName = favouriteMovies.map(function(currItem){return currItem.name});
As you can see I have created a variable called “movieName” and set it to equal to “map” over the “favouriteMovies” array with one parameter defined (the mandatory parameter which represents the current item in the array) and I am returning the key “name” from the “favouriteMovies” array, copy and paste both the map…