.filter()
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Keeping Only Some Elements
You just learned that `map` transforms every element. `filter` selects some of them. Its callback returns `true` to keep an element, `false` to drop it:
const levels = [4, 12, 9, 15];
const high = levels.filter((level) => level >= 10);
console.log(high);The result is a new array with only the approved elements, in their original order. The original array is untouched.
const kept = array.filter((element) => condition);Exercise 2 — The Callback Is a Test
The callback must return a boolean. Any comparison works:
const moves = ["Spark", "Splash", "Thunder", "Vine"];
const short = moves.filter((move) => move.length <= 5);
console.log(short);The callback can also be a function you already have, stored in a variable:
const isElectric = (move) => move === "Spark" || move === "Thunder";
const moves = ["Spark", "Splash", "Thunder", "Vine"];
const electric = moves.filter(isElectric);
console.log(electric);Notice the second example: `filter(isElectric)` passes the function itself. No need to wrap it in another arrow.
Exercise 3 — Quiz: Filtered
What does `result` contain?
const hp = [0, 45, 0, 30];
const result = hp.filter((value) => value > 0);[45, 30][0, 0][true, false]2Hint : Keep only the elements that pass the test.
Exercise 4 — Only the Strong
Keep the levels strictly above 5.
Hint : The method that selects, and the comparison that means "strictly above".
Exercise 5 — Filtering Objects
With an array of objects, the test looks at a property. Here we keep the Codémon that can still fight:
const team = [
{ name: "Aquachu", hp: 40 },
{ name: "Pyrochu", hp: 0 },
{ name: "Zap", hp: 25 }
];
const ready = team.filter((cdm) => cdm.hp > 0);
console.log(ready.length);
console.log(ready[0].name);The kept elements are the same objects, not copies. `ready[0]` is Aquachu's original object.
Exercise 6 — Quiz: How Many Kept?
What does this code print?
const team = [
{ name: "Aquachu", type: "water" },
{ name: "Pyrochu", type: "fire" },
{ name: "Metachu", type: "metal" }
];
const notFire = team.filter((cdm) => cdm.type !== "fire");
console.log(notFire.length);2130Hint : Count the objects for which the test is true.
Exercise 7 — When Nothing Matches
If no element passes the test, `filter` returns an empty array, not `undefined` and not an error. Check `length` to know:
const levels = [3, 5, 2];
const high = levels.filter((level) => level > 10);
console.log(high.length);And if every element passes, you get a full copy of the array. `filter` can return anywhere between 0 and all the elements.
Exercise 8 — Fighters Only
Keep only the members whose HP is above 0, then print how many there are.
Hint : Test the right property, then count the result like any array.
Exercise 9 — Quiz: filter or map?
You want only the names longer than 4 characters, unchanged. Which method fits?
names.filter((n) => n.length > 4)names.map((n) => n.length > 4)names.forEach((n) => n.length > 4)names.length > 4Hint : One method selects, the other transforms every element.
Exercise 10 — filter Cheat Sheet
Match each element with its description.
arr.filter(fn)Exercise 11 — Battle Roster
Sort the team into groups with `filter`, then report on each group.
Step 1: build `ready`, the members with HP strictly above 0. Step 2: build `fainted`, the members with HP equal to 0. Step 3: build `veterans`, the members whose level is 10 or more. Step 4: print `"Ready: N"`, `"Fainted: N"` and `"Veterans: N"`, then the name of each veteran on its own line with `"* "` in front.
Expected output:
Ready: 3
Fainted: 1
Veterans: 2
* Aquachu
* Metachuconst team = [
{ name: "Aquachu", hp: 40, level: 12 },
{ name: "Pyrochu", hp: 0, level: 8 },
{ name: "Zap", hp: 25, level: 4 },
{ name: "Metachu", hp: 60, level: 15 }
];
// Write your code here