.map()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Transforming Every Element
From time to time, you need to turn a whole array into a new one. Let's say every Codémon of your team gained a level after a big fight: you want the same list, with every level increased by 1. With a loop, it takes several lines:
const levels = [5, 8, 3];
const newLevels = [];
for (let level of levels) {
newLevels.push(level + 1);
}
console.log(newLevels);`map` does exactly that in one line. It calls the callback on each element and collects the returned values into a new array:
const levels = [5, 8, 3];
const newLevels = levels.map((level) => level + 1);
console.log(newLevels);const newArray = array.map((element) => transformedElement);Exercise 2 — Same Length, New Values
The new array always has the same number of elements as the original: one result per element. The type can change, though. Here numbers become strings:
const levels = [5, 8, 3];
const labels = levels.map((level) => "Lv." + level);
console.log(labels);
console.log(labels.length);And the original array is untouched. `map` never modifies it, it builds a new one:
const names = ["aquachu", "zap"];
const upper = names.map((name) => name.toUpperCase());
console.log(upper);
console.log(names);Exercise 3 — Quiz: Mapped Values
What does `result` contain?
const hp = [10, 20, 30];
const result = hp.map((value) => value + 5);[15, 25, 35][10, 20, 30][5, 5, 5]65Hint : Apply the callback to each element and collect the results.
Exercise 4 — Triple Everything
Build `tripled` from `levels`, with every level multiplied by 3.
Hint : The method that builds a new array, an arrow, and the operation for a triple.
Exercise 5 — map With Objects
The most common use: extracting one property from each object in a list.
const team = [
{ name: "Aquachu", level: 12 },
{ name: "Pyrochu", level: 8 }
];
const names = team.map((cdm) => cdm.name);
console.log(names);Or building a message from each object:
const team = [
{ name: "Aquachu", level: 12 },
{ name: "Pyrochu", level: 8 }
];
const lines = team.map((cdm) => cdm.name + " is level " + cdm.level);
lines.forEach((line) => console.log(line));Exercise 6 — Quiz: Extract a Property
What does `levels` contain?
const team = [
{ name: "Zap", level: 3 },
{ name: "Metachu", level: 12 }
];
const levels = team.map((cdm) => cdm.level);[3, 12]["Zap", "Metachu"]15[3]Hint : The callback picks one value out of each object.
Exercise 7 — The return Trap
`map` collects what the callback returns. If you use braces and forget `return`, every element becomes `undefined`:
const levels = [5, 8];
const broken = levels.map((level) => {
level * 2;
});
console.log(broken[0]);Add the `return` and the values come back:
const levels = [5, 8];
const fixed = levels.map((level) => {
return level * 2;
});
console.log(fixed[0]);Don't forget, without braces, there is no `return` needed: the value is returned automatically.
const levels = [5, 8];
const short = levels.map((level) => level * 2);
console.log(short[0]);Same rule as for any arrow function: no braces means implicit return, braces mean you must write `return`.
Exercise 8 — Name Tags
Build `tags` containing `"[name]"` for each member, for example `"[Zap]"`.
Hint : You need a new array, built from one property of each object.
Exercise 9 — Quiz: map or forEach?
You want a new array with every price doubled. Which method fits?
prices.map((p) => p * 2)prices.forEach((p) => p * 2)prices.push(p * 2)prices.length * 2Hint : One method produces a new array, the other produces nothing.
Exercise 10 — map Cheat Sheet
Match each element with its description.
arr.map(fn)arr.map((x) => { x * 2; })Exercise 11 — Level Up Everyone
The whole team wins a battle. Use `map` to build new data without modifying the original arrays.
Step 1: build `newLevels`, an array of numbers: each member's level plus 1. Step 2: build `announcements`, an array of strings: `"name reached level X"` using the new level. Step 3: print every announcement on its own line. Step 4: print `"Original: X"` with the level of the first member in the original `team`, to prove it didn't change.
Expected output:
Aquachu reached level 13
Pyrochu reached level 9
Zap reached level 5
Original: 12const team = [
{ name: "Aquachu", level: 12 },
{ name: "Pyrochu", level: 8 },
{ name: "Zap", level: 4 }
];
// Write your code here