본문 바로가기
개념/혼자 공부하는 Javascript

method) filter()

by kiseno 2025. 1. 12.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        const numbers = [0,1,2,3,4,5]
        const evenNumbers = numbers.filter(function(value){
            return value % 2 === 0
        })

        console.log(`original array : ${numbers}`)
        console.log(`even array : ${evenNumbers}`)
    </script>
</head>
<body>

</body>
</html>

### JavaScript Breakdown
- **Initialization of the Array**: An array named `numbers` is defined with integers from 0 to 5 inclusive.

- **Filtering Even Numbers**: The `filter` method is applied to the `numbers` array. This method takes a callback function that is executed on each element of the array. The callback function returns `true` or `false` for each element based on the condition provided (`value % 2 === 0`). For even numbers, the condition evaluates to `true`, and those numbers are included in the new array `evenNumbers` that `filter` returns. Essentially, `evenNumbers` ends up containing only the even numbers from the `numbers` array.

- **Logging the Arrays**: The original `numbers` array and the newly created `evenNumbers` array are logged to the console. This action demonstrates the result of the filtering operation.

### Expected Console Output
The console will display the following lines showing the original array and the filtered array containing only even numbers:

```
original array : 0,1,2,3,4,5
even array : 0,2,4
```

### Summary
This example effectively illustrates how to use the `filter` method to selectively include elements from an original array into a new array based on a specified condition. In this case, the condition is that an element must be an even number. This is a common pattern in JavaScript for creating subsets of data that match certain criteria, showcasing a fundamental aspect of array manipulation in web development.

728x90
반응형
LIST