.flat() and .flatMap()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Flattening Nested Arrays
Imagine your Codémon storage boxes are organized as an array of smaller sub-arrays. If you want to gather every Codémon from every box into a single simple array, you can use `.flat()`.
The `.flat()` method removes the inner array brackets and returns a new array containing all the elements in one single list:
const boxes = [["Aquachu", "Zap"], ["Pyrochu"], ["Florachu", "Rockachu"]];
console.log(boxes.length);
const allCodemon = boxes.flat();
console.log(allCodemon.length);
console.log(allCodemon);Here, `boxes` had 3 sub-arrays, and `boxes.flat()` unpacked them into a new array of 5 Codémon without modifying `boxes`.
Exercise 2 — How Deep to Go
By default, `.flat()` only unwraps 1 level of nested arrays. If there are arrays nested several levels deep, you can pass a depth number to tell `.flat()` how many levels to unwrap:
const nested = ["Aquachu", ["Pyrochu", ["Zap", ["Florachu"]]]];
console.log(nested.flat(1).length);
console.log(nested.flat(2).length);If you want to flatten every single level no matter how deeply nested the arrays are, pass `Infinity`:
const nested = ["Aquachu", ["Pyrochu", ["Zap", ["Florachu"]]]];
console.log(nested.flat(Infinity));Exercise 3 — Quiz: How Many After flat?
What does this code print?
const groups = [[1, 2], [3], [4, 5, 6]];
console.log(groups.flat().length);6321Hint : Add up the sizes of the inner arrays.
Exercise 4 — One Big List
Turn the groups into a single list and print how many names it holds.
Hint : One method opens the inner arrays, then the result is measured as usual.
Exercise 5 — map Then flat, in One Step
Suppose each Codémon in your `team` has an array of `moves`, and you want a single list containing all moves from the entire team. If you use `.map((cdm) => cdm.moves)`, each Codémon returns its own array, leaving you with an array of arrays (`[["Splash", "Wave"], ["Spark"]]`) that you then have to `.flat()`:
const team = [
{ name: "Aquachu", moves: ["Splash", "Wave"] },
{ name: "Zap", moves: ["Spark"] }
];
const nestedMoves = team.map((cdm) => cdm.moves);
console.log(nestedMoves);
const allMoves = nestedMoves.flat();
console.log(allMoves);`.flatMap()` is a built-in shortcut that does `.map()` followed by `.flat()` in one single step:
const team = [
{ name: "Aquachu", moves: ["Splash", "Wave"] },
{ name: "Zap", moves: ["Spark"] }
];
const allMoves = team.flatMap((cdm) => cdm.moves);
console.log(allMoves);Exercise 6 — Quiz: flatMap Result
What does `r` contain?
const team = [
{ moves: ["a", "b"] },
{ moves: ["c"] }
];
const r = team.flatMap((c) => c.moves);["a", "b", "c"][["a", "b"], ["c"]]3[]Hint : The method transforms and then opens one level.
Exercise 7 — All the Moves
Build a single list of every move of the team.
Hint : One method transforms and flattens at once, and the callback returns the inner list.
Exercise 8 — flat vs flatMap
Match each element with its description.
arr.flat()arr.flat(Infinity)arr.flatMap(f)arr.map(f).flat()Exercise 9 — Move Encyclopedia
Build the gym's move encyclopedia from a list of Codémon, each with its own move list.
Step 1: build `allMoves`, a single flat list of every move of the roster, and print `"Total moves: N"`. Step 2: print the moves sorted alphabetically, joined with `", "`. Step 3: print `"Long moves: N"` with the number of moves longer than 5 characters. Step 4: `groups` holds Codémon names grouped by trainer. Flatten it and print `"Trainers' Codémon: N"` with the total.
Expected output:
Total moves: 5
Charge, Flame, Spark, Splash, Wave
Long moves: 2
Trainers' Codémon: 4const roster = [
{ name: "Aquachu", moves: ["Splash", "Wave"] },
{ name: "Zap", moves: ["Spark", "Charge"] },
{ name: "Pyrochu", moves: ["Flame"] }
];
const groups = [["Aquachu", "Zap"], ["Pyrochu"], ["Metachu"]];
// Write your code here