Converting Elements: map()
Another loop you know well goes through an array and makes something new out of each element. This one makes an array of the names of the zoo animals from the previous exercise:
const names = [];
for (const animal of animals) {
names.push(animal.name);
}
console.log(names);["Ella", "Leo", "Gina", "Pip"]That's what the method map() is for:
const names = animals.map((animal) => animal.name);
console.log(names);["Ella", "Leo", "Gina", "Pip"]map() calls the callback for each element too, and whatever the callback returns goes into the new array, in the same order. So the new array always has as many elements as the original one. The callback can return anything: a property, a calculation or a text.
const ages = animals.map((animal) => animal.age);
const agesNextYear = ages.map((age) => age + 1);
const labels = animals.map((animal) => `${animal.name} the ${animal.species}`);
console.log(agesNextYear);
console.log(labels);[13, 7, 5, 3]
["Ella the elephant", "Leo the lion", "Gina the giraffe", "Pip the penguin"]Like filter(), map() doesn't change the original array: ages is still [12, 6, 4, 2].
In many programs, you'll also see the method forEach(). It calls the callback for each element as well, but it doesn't create a new array. It's just another way to write a for...of loop:
animals.forEach((animal) => console.log(animal.name));Ella
Leo
Gina
PipThis does the same as for (const animal of animals) { console.log(animal.name); }, so use whichever you like. When you need a new array, use map().
A typical mistake is a callback with curly braces but without return. animals.map((animal) => { animal.name; }) gives [undefined, undefined, undefined, undefined], because the callback returns nothing for any of the animals.
Instructions
Rewrite the loop that fills names with map(): const names = players.map(...);. Remove the empty array and the loop. The program then prints the same as before: ["Kate", "Mia", "Zoe", "Lily"].
Below, create a constant shirts with map(): for each player, a text with the name and the number in parentheses, like "Kate (7)". Print shirts.
The scoreboard shows the names in capital letters. Create a constant scoreboard from names with map() and toUpperCase(), and print it: ["KATE", "MIA", "ZOE", "LILY"].