You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
map exists as a method on all arrays, it takes one uncalled function as an argument
This uncalled function is called for each item in the array, as map iterates over each item
This function is provided the value currently being iterated over as the first parameter, in the above
case, that means that pet represents {type: 'Dog', age: 5} the first time it is called, then {type: 'Cat', age: 11} the second time,
and then {type: 'Dog', age: 9} the third.
Whatever is returned in that function ends up in the new array at the same index
In the above example, the first time pet.type is equal to Dog, therefore what is returned is pet.age * dogToHumanYearMultiplier,
which the first time evaluates to 5 * 7, which means that in the new array at the first index, the value is 35
Useful Tips
Often we want to create new arrays of objects, where we just update the object
constlistOfPets=[{type: 'Dog',age: 5},{type: 'Cat',age: 11},{type: 'Dog',age: 9}];constdogToHumanYearMultiplier=7;constcatToHumanYearMultiplier=4;// keep the list of pets, just add a new property for the human yearsconstupdatedListOfPets=listOfPets.map(pet=>Object.assign({},pet,{inHumanYears: pet.type==='Dog' ? pet.age*dogToHumanYearMultiplier : pet.age*catToHumanYearMultiplier}));
The above uses Object.assign() - a useful method that merges objects together, when used correctly, it provides you an
immutable solution to updating objects
// DO NOT DO THISconstlistOfPets=[{type: 'Dog',age: 5},{type: 'Cat',age: 11},{type: 'Dog',age: 9}];constdogToHumanYearMultiplier=7;constcatToHumanYearMultiplier=4;constupdatedListOfPets=listOfPets.map(pet=>pet.inHumanYears=pet.type==='Dog' ?
pet.age*dogToHumanYearMultiplier : pet.age*catToHumanYearMultiplier);
In the above example, you are modifying the original listOfPets