0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Javasctipt】filter関数とmap関数の使い分け

Last updated at Posted at 2025-02-03

filter関数とmap関数はどちらも配列を操作する関数です。

今回はそれぞれの使い方と使い分けについてまとめてみます。

filter関数とは?

filter関数は、配列の要素を条件に基づいてフィルタリングし、新しい配列を返すメソッドです。

元々の配列は変更されず、条件に一致した要素のみを含む新しい配列が作成されます。

const numbers= [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4, 6]

使用例

・配列から特定の条件に合う要素のみを抽出
・フラグがtrueのデータのみを取得
・ユーザーのアクティブなデータを取得
・不要なデータを取り除く(空文字列を削除する)

map関数とは?

map関数は、配列の各要素に対して処理を行い、その結果を含む新しい配列を返すメソッド。

filter関数と同様に、元の配列が変更されることはない。

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

使用例

・配列の要素を変換する
・数値を文字列に変換する
・UI用にデータのフォーマットを変更する
・IDのリストを取得する
・JSONデータをオブジェクトに変換する

ユーザーの名前を取得

const users=[
{id:1,name:'Alice',isActive:true},
{id:2,name:'Bob',isActive:false},
{id:3,name:'Charlie',isActive:true}
];

const userName=users.map(user=>user.name);
consolelog(userNames);// ["Alice", "Bob", "Charlie"]
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?