자바스크립트 배열 필터링(Filtering)

Filtering an array in JavaScript is a common operation that allows you to easily extract specific elements based on a certain condition. It is a useful technique when you want to manipulate or display only a subset of data from an array.

The filter() Method

JavaScript provides the filter() method which allows you to create a new array containing elements that pass a certain condition. The filter() method applies a given callback function to each element in the array and returns a new array with only the elements for which the callback function returned true.

Here’s the syntax of the filter() method:

array.filter(callback(element[, index[, array]])[, thisArg])

Example: Filtering Even Numbers

Let’s say we have an array of numbers and we want to filter out only the even numbers. We can achieve this using the filter() method with a simple callback function.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const evenNumbers = numbers.filter(num => num % 2 === 0);

console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]

In the above example, the callback function num => num % 2 === 0 checks if each element is divisible by 2 with no remainder. If the result is true, the element is added to the evenNumbers array.

Example: Filtering Strings

Filtering arrays is not limited to numbers only, as you can also filter arrays of strings or any other data type.

const fruits = ['apple', 'banana', 'orange', 'pear', 'grape'];

const filteredFruits = fruits.filter(fruit => fruit.length > 5);

console.log(filteredFruits); // Output: ['banana', 'orange']

In the above example, we filter the fruits array to only include fruits with a length greater than 5.

Summary

Filtering arrays in JavaScript can be easily done using the filter() method. It allows you to create a new array containing elements that pass a certain condition. You can customize the filtering logic by providing a callback function that determines whether an element should be included in the filtered array.