feat(curriculum): Add interactive examples to Filter method lesson (#63399)

This commit is contained in:
Giftea ☕
2025-10-31 21:26:55 +01:00
committed by GitHub
parent 188b721b62
commit 86c334b81f

View File

@@ -5,12 +5,14 @@ challengeType: 19
dashedName: what-is-the-filter-method-and-how-does-it-work
---
# --description--
# --interactive--
The `filter` method is used to create a new array with elements that pass a specified test, making it useful for selectively extracting items based on criteria.
In this example, we are using the `filter` method, to create a new array of only even numbers:
:::interactive_editor
```js
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
@@ -18,6 +20,8 @@ const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6, 8, 10]
```
:::
In this example, the `filter` method applies a callback function to each element of the `numbers` array. The callback checks whether each number is even using the modulo operator (`%`).
If the number is even, the function returns `true`, and that number is included in the new array. If it's odd, the function returns `false`, and that number is excluded.
@@ -26,17 +30,23 @@ Just like the `map` method, the callback function for the `filter` method accept
It's important to note that if no elements pass the test, the `filter` method returns an empty array.
:::interactive_editor
```js
const numbers = [2, 4, 6, 8].filter((num) => num > 10);
console.log(numbers); // []
```
:::
`filter` is incredibly versatile and can be used in many scenarios. You can use it to remove `null` or `undefined` values from an array, to filter objects based on their properties, or to implement search functionality.
Here's an example of using the `filter` method to return an array of objects for individuals younger than `30` years old.
```javascript
:::interactive_editor
```js
const developers = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
@@ -50,6 +60,8 @@ console.log(youngPeople);
// [{ name: "Alice", age: 25 }, { name: "David", age: 25 }]
```
:::
Throughout the rest of this curriculum, you will be using the `map` and `filter` methods very frequently. So, building familiarity with them will not only streamline your coding process but also help you write cleaner and more efficient code.
# --questions--