Javascript map()
creates a new array, which contains the results obtained from iterating over the elements of the specified array
and calling the provided function once for each element in order.
Note:
map()
only works on arrays. It does not execute a function for an empty array.
The syntax is as follows:
array: the array on which the specified function is called.
map: the method called for the array with the required parameters.
function(currentValue, index, arr): the function with its parameters which is required to run for each element of the array.
currentValue: the value of the current element.
index: the index of the current element being processed.
arr: the array object on which map()
is called.
thisValue: value to be used as the function’s this
value when executing it. “undefined” will be passed if this value is not provided.
Note: index, arr and thisValue are all optional parameters.
Now let’s take a look at an example of an implementation of the map()
function.
//creating an arrayvar my_array = [1, 3, 5, 2, 4];//map calls a function which has "item" passed as parameter//map will pass each element of my_array as "item" in this function//the function will double each element passed to it and return itresult = my_array.map(function(item) {return item*2;});//prints new list containing the doubled valuesconsole.log(result);
Note: Since a new array is returned at the end,
map()
does not change the original array.
The above example didn’t use any additional parameters.
Let’s look at an example with optional parameters passed into the function:
var my_array = [1,3,5,2,4];my_array.map(function(item,index,arr) {console.log("item: " + item + " at index: " + index + " in the array: " + arr);});