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】配列操作メソッド解説

Posted at

はじめに

JavaScriptで配列を扱う際によく使うメソッドについて解説します。それぞれのメソッドの特徴と使い分けを理解しておくと、コードがより読みやすく効率的になりますね。

配列を操作する主要なメソッド

forEach

配列の各要素に対して、指定した関数を順番に実行するメソッドです。for...of文と同様の役割を持ちますが、関数型プログラミングのスタイルで記述できます。

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

// 各要素をコンソールに出力する
numbers.forEach(function (num) {
  console.log(num * 2);
});
// 出力: 2, 4, 6, 8, 10

// forEachは戻り値を返さない(undefinedを返す)
const result = numbers.forEach(num => num * 2);
console.log(result); // undefined

特徴: 戻り値がないため、副作用を伴う処理に使用します。

map

配列の各要素を変換して、新しい配列を生成するメソッドです。forEachとの大きな違いは、変換後の値をreturnすることで新しい配列が作られる点です。

メソッドの引数に渡す関数のことをコールバック関数と呼びます。

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

// 各要素を2倍にした新しい配列を作る
const doubled = numbers.map(function (num) {
  return num * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5] (元の配列は変更されない)

特徴: 元の配列を変更せず、変換後の新しい配列を返します。

filter

配列から特定の条件を満たす要素だけを抽出して、新しい配列を生成するメソッドです。

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

// 偶数だけを抽出
const evenNumbers = numbers.filter(function (num) {
  return num % 2 === 0;
});

console.log(evenNumbers); // [2, 4, 6]
console.log(numbers); // [1, 2, 3, 4, 5, 6] (元の配列は変更されない)

特徴: コールバック関数がtrueを返した要素のみが新しい配列に含まれます。

every

配列の全ての要素が指定した条件を満たすかどうかを判定し、真偽値を返すメソッドです。

const numbers = [2, 4, 6, 8];

// 全て偶数かチェック
const allEven = numbers.every(function (num) {
  return num % 2 === 0;
});

console.log(allEven); // true

some

配列の要素の中で少なくとも1つが指定した条件を満たすかどうかを判定し、真偽値を返すメソッドです。

const numbers = [1, 3, 5, 8];

// 偶数が1つでも含まれているかチェック
const hasEven = numbers.some(function (num) {
  return num % 2 === 0;
});

console.log(hasEven); // true (8が偶数)

reduce

配列の各要素を順番に処理して、単一の値にまとめるメソッドです。合計値の計算や最大値・最小値の算出などに使用します。挙動が若干難しく、別で記事を書いているので参考にしてください。

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

// 配列の合計を計算
const sum = numbers.reduce(function (accumulator, current) {
  return accumulator + current;
}, 0); // 0は初期値

console.log(sum); // 15

// 最大値を求める
const max = numbers.reduce(function (acc, num) {
  return num > acc ? num : acc;
});

console.log(max); // 5

特徴: accumulator(累積値)とcurrent(現在の要素)を受け取り、処理結果を次の反復に渡していきます。

メソッドの使い分け

まとめ

各メソッドの特徴を理解して、目的に応じて使い分けることが重要です。mapfilterreduceは関数型プログラミングの基本となるメソッドなので、ぜひ使いこなせるようになりましょう。

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?