Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Filtering Arrays with filter | Transforming and Searching Arrays
JavaScript Array Methods

bookFiltering Arrays with filter

メニューを表示するにはスワイプしてください

The filter method is a powerful tool in JavaScript for creating a new array that includes only those elements from an existing array that satisfy a specific condition. When you use filter, you provide a callback function that tests each element. If the callback returns true for an element, that element is included in the new array; if it returns false, the element is excluded. This makes filter especially useful for extracting subsets of data, such as finding all users over a certain age, selecting completed tasks, or narrowing down items based on search criteria.

12345
const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4, 6]
copy

One important aspect of filter is that it does not modify the original array. Instead, it returns a new array containing only the elements that passed the test. This concept is called immutability. By leaving the original array unchanged, filter helps prevent unexpected side effects in your code, making it easier to reason about data flow and transformations.

Note

You can also chain filter with other array methods, such as map or sort, to perform more advanced transformations in a single, readable line of code. This makes it easy to build complex data processing pipelines while keeping your code clean and expressive.

1. Which of the following will be the output of the code below?

2. Complete the callback function to filter an array of numbers, returning only those greater than 10.

question mark

Which of the following will be the output of the code below?

正しい答えを選んでください

question-icon

Complete the callback function to filter an array of numbers, returning only those greater than 10.

const numbers = [5, 12, 8, 130, 44]; const largeNumbers = numbers.filter(function(num) { return ; }); console.log(largeNumbers); // Output should be: [12, 130, 44]
[12, 130, 44]

クリックまたはドラッグ`n`ドロップして空欄を埋めてください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  2
some-alt