0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript 配列 filter()関数

0
Posted at

😄この投稿は、codingeverybody.jpのコンテンツをもとに作成しています。

定義と使い方

配列のfilter()関数は、コールバック関数を使用して配列の要素をフィルタリングします。
この関数を使用すると、配列の要素の中から必要な値だけを簡単に抽出できます。
条件をコールバック関数として記述すると、その条件を満たす要素だけが新しい配列として返されます。

特徴

  • フィルタリングの条件はコールバック関数内で適用します。:条件を満たす場合はtrueを、満たさない場合はfalseを返すように記述する必要があります。
  • 元の配列はそのまま保持され、条件を満たす要素だけで構成された新しい配列が返されます。

基本例

次は、filter()関数を使用して配列の要素の中から偶数だけをフィルタリングし、フィルタリングされた配列として返す例です。

// フィルタリングする配列
const num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// 開発者が直接作成したコールバック関数
function isEven(value) {
    return value % 2 === 0; // 偶数の場合はtrueを返す
}

// 配列の要素を走査し、フィルタリングされた配列として返す
const result = num.filter(isEven);
console.log(result); // 出力:[2, 4, 6, 8, 10]

例のように、コールバック関数は各要素に対して条件を評価し、要素をフィルタリング(保持)する場合はtrueを、そうでない場合はfalseをreturnで返す必要があります。filter()関数は各要素を順に処理し、コールバック関数でreturnとしてtrueを返した要素だけを集めて新しい配列として返します。

構文

arr.filter(callbackFn)
arr.filter(callbackFn, thisArg)

活用例

# 配列の重複要素を削除する

const numbers = [1, 2, 2, 3, 4, 4, 5];

const uniqueNumbers = numbers.filter((element, index, arr) => {
    // 現在の要素が以前に出現していない場合のみtrueを返す
    return arr.indexOf(element) === index;
});

console.log(uniqueNumbers); // 出力:[1, 2, 3, 4, 5]

# 複数条件でのフィルタリング

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

const filteredNumbers = numbers.filter(element => {
    // 複数条件を組み合わせてフィルタリング
    return element % 2 === 0 && element < 5;
});

console.log(filteredNumbers); // 出力:[2, 4]

# 2次元配列のフィルタリング

// 2次元配列の作成
const students = [
    ["Alice", 25],
    ["Bob", 30],
    ["Charlie", 22],
    ["David", 35]
];

// 年齢が30以上の学生だけをフィルタリング
const filteredStudents = students.filter(student => {
    // student配列の2番目の要素(年齢)が30以上の場合のみtrueを返す
    return student[1] >= 30;
});

console.log(filteredStudents); // 出力:[["Bob", 30], ["David", 35]]

# 文字列配列から長さが5以上の文字列をフィルタリング

const words = ["apple", "banana", "cherry", "date", "fig"];
const longWords = words.filter((word) => word.length >= 5);
console.log(longWords); // 出力:[ "apple", "banana", "cherry" ]

参考資料

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?