ES6における配列操作とユーティリティメソッドの実践ガイド

配列の初期化と変換

ES6では、従来の配列作成方法に加え、より柔軟で意図が明確な静的メソッドが導入されました。

// 伝統的な構文(互換性維持用)
const legacyArray = new Array(1, 2, 3);
const literalArray = [4, 5, 6];

// Array.of():引数をそのまま要素とする新しい配列を生成
console.log(Array.of('a', null, { id: 1 })); // ['a', null, { id: 1 }]
console.log(Array.of()); // []

// Array.from():反復可能オブジェクトや疑似配列から真の配列へ変換
console.log(Array.from('abc')); // ['a', 'b', 'c']
console.log(Array.from(new Set([1, 2, 2]))); // [1, 2]

// map関数とthisコンテキストを指定可能
const context = { multiplier: 3 };
const transformed = Array.from([2, 4, 6], function(x) {
  return x * this.multiplier;
}, context);
console.log(transformed); // [6, 12, 18]

要素検索と存在確認

従来のindexOfやfilterによる探索に代わる、意味的かつ効率的な代替手段です。

const numbers = [10, 20, 30, 40, 50];

// find(): 条件を満たす最初の値を返す(undefinedも含む)
console.log(numbers.find(n => n > 25)); // 30

// findIndex(): 対応するインデックスを返す
console.log(numbers.findIndex(n => n === 40)); // 3

// includes(): 値の存在をBooleanで判定(NaNにも対応)
console.log([1, 2, NaN].includes(NaN)); // true
console.log(['x', 'y'].includes('z')); // false

範囲ベースの変更操作

特定のインデックス範囲に対して一括で値を書き換える機能です。

let data = [100, 200, 300, 400, 500];

// fill(): 指定範囲を単一値で埋める
data.fill('X', 1, 4); // [100, 'X', 'X', 'X', 500]

// copyWithin(): 自身の別の領域から値をコピーして上書き
const buffer = [1, 2, 3, 4, 5];
buffer.copyWithin(0, 3); // [4, 5, 3, 4, 5](index3〜末尾をindex0から上書き)
buffer.copyWithin(-2, 0, 2); // [1, 2, 3, 1, 2](先頭2要素を末尾2要素にコピー)

反復処理とデータ変換

副作用の有無や戻り値の型に応じて、適切な高階関数を選択します。

const items = ['apple', 'banana', 'cherry'];

// forEach(): 副作用のみ(戻り値はundefined)
items.forEach((fruit, idx) => console.log(`${idx}: ${fruit}`));

// map(): 元の長さと同じ新配列を生成
const lengths = items.map(fruit => fruit.length); // [5, 6, 7]

// filter(): 条件に合致する要素のみ抽出
const longNames = items.filter(fruit => fruit.length > 5); // ['banana', 'cherry']

// every()/some(): 論理条件の集約
console.log(items.every(f => f.includes('a'))); // true
console.log(items.some(f => f.startsWith('c'))); // true

集約演算とデータ構造変換

reduceは汎用性が高く、様々な集約タスクに活用できます。

// 単純な合計
const sum = [1, 2, 3, 4].reduce((acc, curr) => acc + curr, 0); // 10

// ネスト解除(フラット化)
const nested = [[1, 2], [3], [4, 5, 6]];
const flat = nested.reduce((acc, sub) => [...acc, ...sub], []); // [1, 2, 3, 4, 5, 6]

// 頻度カウント(オブジェクト形式)
const fruits = ['kiwi', 'mango', 'kiwi', 'pear'];
const frequency = fruits.reduce((map, item) => {
  map[item] = (map[item] || 0) + 1;
  return map;
}, {}); // { kiwi: 2, mango: 1, pear: 1 }

// 重複排除(Set経由が推奨)
const unique = [...new Set([1, 2, 2, 3, 3, 4])]; // [1, 2, 3, 4]
const uniqueAlt = Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]

タグ: ES6 javascript arrays REDUCE map

8月1日 03:23 投稿