2
4

More than 1 year has passed since last update.

【JavaScript】filter()の使い方

Posted at

filter()の使い方

filter()は、コールバック関数で指定された条件を満たす要素だけを取り出して新しい配列を生成するメソッド。filter()の基本的な書き方は以下となる。

// arrayは配列
array.filter((element, index, array) => {
    // 処理内容
});

上記のようにコールバック関数は以下の3つの引数を取る。ただし、indexarrayについては省略可能。
element : 配列の要素の値
index : 配列のインデックス
array : 処理対象の配列
また、コールバック関数は既に削除済みや未代入の添字に対しては呼び出されず、値が代入されているもののみが呼び出される。

filter()を使って配列の要素から偶数だけを取り出す簡単なサンプルが以下となる。

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = array.filter((value) => {
    return value % 2 === 0;
});
console.log(result);    // [ 2, 4, 6, 8, 10 ]

また、オブジェクトを要素に持つ配列の場合のサンプルが以下となる。

const array = [
    { id: 1, score: 70 },
    { id: 2, score: 50 },
    { id: 3, score: 55 },
    { id: 4, score: 85 },
    { id: 5, score: 60 },
];

const result = array.filter((value) => {
    return value.score >= 60;
});
console.log(result);    // [ { id: 1, score: 70 }, { id: 4, score: 85 }, { id: 5, score: 60 } ]

もし条件を満たす要素が存在しない場合は空の配列[]が返される。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4