The map method allows you to iterate over an array and do whatever you want on each item in that array and creates a new array with the desired output without modifying the original array.
So the first question here, how can i write what i want to do on each item ?
The answer is simple, the map method takes a function as a parameter called callback function this function is executed on each item of the array and the resulting output of that function is stored in the new array that map creates.
Now, let’s take a closer look at that function called callback function.
like any function, it can take parameters.
So, what parameters can this callback function have?
Logically, you say that this function is executed on each item of the array. So how does it know the value of that item ?
Here comes the first parameter this function can have: THE ITEM VALUE
( or the item in general cause it can be an object for example )
It can have more parameters related to this item, which i will put the MDN documentation link at the bottom so you can read more.
For Example:
const arr1 = [2, 3, 4, 9];
const arr2 = arr1.map((item) => {
return item * 2;
});
console.log(arr2); // output: [4, 6, 8, 18]
console.log(arr1); // output: [2, 3, 4, 9]
As you can see, the arr1 didn’t change at all. Instead, we used the map function to take each item on the arr1 array and then doubled its value and return which indicate that this is the final result that should be stored in the new array arr2 for this item.
Last Example to help you on your issue:
const arrOfObjects = [
{
"Title": "Inception",
"Runtime": "148 min",
"imdbRating": "8.8"
},
{
"Title": "Interstellar",
"Runtime": "169 min",
"imdbRating": "8.6"
}
]
Now I have an array containing two objects. So what if i want to create a new array also with two objects but with the Title and Runtime properties only but with different names for example the Title is name and Runtime is duration ?
Well, as long as it’s an array I can use the map array method as I think now we know how to use it.
const newArr = arrOfObjects.map((movie) => {
return {
"name": movie["Title"],
"duration": movie["Runtime"]
}
})
console.log(newArr);
// output:
[
{
"name": "Inception",
"duration": "148 min"
},
{
"name": "Interstellar",
"duration": "169 min"
}
]
Now you are taking each item in that array which is an object this time not a number.
Read more: MDN documentation