JavaScript Array.filter() メソッド - 条件に合う要素を選択

Array.filter()をマスターして条件に合う要素を選択。オブジェクトのフィルタリング、mapとのチェーン、TypeScript型の絞り込み例を含みます。無料リファレンス。

Iteration

詳細な説明

Array.filter()を理解する

Array.filter()は、提供されたコールバック関数によるテストに合格した要素のみを含む新しい配列を作成します。truthyな値を返す要素は保持され、falsyを返す要素は除外されます。

構文

const filtered = array.filter((element, index, array) => {
  // 保持するにはtrue、除外するにはfalseを返す
});

基本例

// 偶数のみを保持
const nums = [1, 2, 3, 4, 5, 6];
const evens = nums.filter(n => n % 2 === 0);
// evens: [2, 4, 6]

// プロパティでオブジェクトをフィルタ
const users = [
  { name: "Alice", active: true },
  { name: "Bob", active: false },
  { name: "Carol", active: true }
];
const activeUsers = users.filter(u => u.active);
// activeUsers: [{name:"Alice",...}, {name:"Carol",...}]

filterとmapのチェーン

非常に一般的なパターンはフィルタリングしてから変換すること:

const products = [
  { name: "Widget", price: 25, inStock: true },
  { name: "Gadget", price: 50, inStock: false },
  { name: "Doohickey", price: 15, inStock: true }
];

const affordableNames = products
  .filter(p => p.inStock && p.price < 30)
  .map(p => p.name);
// affordableNames: ["Widget", "Doohickey"]

TypeScriptの型の絞り込み

TypeScriptでは、型述語を使用してfilterでユニオン型を絞り込めます:

const mixed: (string | null)[] = ["a", null, "b", null, "c"];
const strings: string[] = mixed.filter(
  (x): x is string => x !== null
);
// strings: ["a", "b", "c"] — string[]として適切に型付け

filter() vs find()

  • filter()すべての一致する要素を新しい配列として返す
  • find()最初の一致のみを返す(またはundefined)

単一の結果が必要な場合はパフォーマンスのためにfind()を使用してください。

ユースケース

filter()は検索機能、リストから削除済みアイテムの除去、表示用のデータサブセットの抽出、元の配列を変更せずに特定の条件に一致する要素を選択する必要があるあらゆるシナリオに使用します。

試してみる — JavaScript Array Methods Reference

フルツールを開く