Each element of the parent array is turned into an array by JavaScripts map() method. An array is iterated over using the map method, which calls a function on every element. You may use the Array.map() method to traverse over an array and alter its elements via a callback function. The callback function will then be run on each element of the array.
array.map(function(currentValue, index, arr), thisValue)
Parameter | Description |
---|---|
function() | For each array element, a function must be executed. |
currentValue | This is the current elements value. |
index | The current elements index number. |
arr | This is the current elements array. |
thisValue | A value that will be used by the function. The default value is undefined. |
Lets imagine we want to multiply our array by 5. Lets see how we can achieve this with a for loop first.
let array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++){
array[i] = array[i] * 5;
}
console.log(array);
[ 5, 10, 15, 20, 25 ]
Lets see how we can iterate over an array using map() method.
let array = [1, 2, 3, 4, 5];
let result = array.map(function(element){
return element * 5;
});
console.log(result);
[ 5, 10, 15, 20, 25 ]
Lets see how we can iterate objects over an array using map() method.
let employee = [
{empID : "101", empName: "Vishal"},
{empID : "102", empName: "Sheshadri"},
{empID : "103", empName: "Aditya"}
];
let empInfo = employee.map(function(element){
return [element.empID,element.empName];
})
console.log(empInfo);
[ [ '101', 'Vishal' ],
[ '102', 'Sheshadri' ],
[ '103', 'Aditya' ] ]
Lets see how we can use function for multiplying
const no = [1, 2, 3, 4, 5];
const array = no.map(multiply)
console.log(array)
function multiply(num) {
return num * 5;
}
[ 5, 10, 15, 20, 25 ]