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のmap()の使い方

Last updated at Posted at 2025-11-09

map() は、配列の各要素に「関数(多くはアロー関数)」を適用して、新しい配列を作るメソッドです。

そしてその「関数」を 引数として渡す(=コールバック関数として渡す)ので、アロー関数がよく使われます。

map()の使い方

🟩 基本構文

const 新しい配列 = 元の配列.map( (要素, インデックス, 配列全体) => {
  // 要素ごとに実行する処理
  return 返したい値;
});

※配列全体を引数で渡すことはあまりないと思いますが、例えば処理の中で array.lengthを使いたい時などの状況があるかなと思います。

🟩 シンプルな例

const numbers = [1, 2, 3];

const doubled = numbers.map((num) => {
  return num * 2;
});

console.log(doubled);
// → [2, 4, 6]

🔹 ここでは

map() が numbers の各要素に対して、アロー関数 (num) => num * 2 を実行し、
その結果を集めて新しい配列 [2, 4, 6] を返します。

🟦 1行の処理なら「return」も省略できます

const doubled = numbers.map(num => num * 2);
console.log(doubled);
// → [2, 4, 6]

波括弧 {} を省略した場合、式の値がそのまま返されます。

🟨 インデックスも使える

map() のコールバック関数は、第2引数にインデックス(要素番号)が渡されます。

const doubled = numbers.map((num, index) => {
  console.log(`${index}番目の要素は ${num}`);
  return num * 2;
});

🟧 オブジェクト配列にもよく使う

const users = [
  { name: "たなか", age: 30 },
  { name: "さとう", age: 40 },
];

const names = users.map(user => user.name);
console.log(names);
// → ["たなか", "さとう"]

🧩 まとめ

目的: 配列の要素を変換して新しい配列を作る
元の配列: 変更されない(非破壊的)
コールバック関数: map() の引数として渡す
よく使う形: アロー関数で簡潔に書く

✅ よく使う形まとめ

// 基本形
arr.map((x) => {
  return x * 2;
});

// 1行省略形
arr.map(x => x * 2);

// オブジェクトから特定の値を取り出す
arr.map(item => item.name);
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?