JavaScriptの Set
と Array
はどちらもコレクション型ですが、それぞれの特性や用途には明確な違いがあります。この記事では、違い・相互変換・集合演算(和・積・差) について実用的に整理します。
Set と Array の違い
比較項目 | Set |
Array |
---|---|---|
値の重複 | 重複不可(自動で排除) | 重複OK |
順序 | 挿入順を保持 | 挿入順を保持 |
要素の型 | 任意の型(オブジェクトも可) | 任意の型 |
イテレーション |
forEach , for...of , Spread可 |
同様に可能 |
ユースケース例 | 一意な値の集合、集合演算 | 順序付きリスト、汎用データ操作 |
Set と Array の相互変換
Array → Set(重複を排除)
const arr = [1, 2, 2, 3];
const set = new Set(arr);
console.log(set); // Set(3) { 1, 2, 3 }
Set → Array
const set = new Set(['a', 'b', 'c']);
const arr = Array.from(set);
// または [...set]
console.log(arr); // ['a', 'b', 'c']
Set による集合演算
集合としての Set
を活用することで、以下のような操作が可能です。
1. 和集合(union)
const a = new Set([1, 2, 3]);
const b = new Set([3, 4, 5]);
const union = new Set([...a, ...b]);
console.log([...union]); // [1, 2, 3, 4, 5]
2. 積集合(intersection)
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const intersection = new Set([...a].filter(x => b.has(x)));
console.log([...intersection]); // [2, 3]
3. 差集合(difference)
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const difference = new Set([...a].filter(x => !b.has(x)));
console.log([...difference]); // [1]
4.排他的論理和(exclusiveor)
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
const xor = new Set([
...[...a].filter(x => !b.has(x)),
...[...b].filter(x => !a.has(x))
]);
Set を活用する実用シーン
-
配列の重複削除:
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]
-
値の存在確認(高速):
const ids = new Set(['user1', 'user2']); if (ids.has('user2')) { // true }
-
大量データに対する高速検索や比較操作
まとめ
やりたいこと | おすすめ |
---|---|
重複を排除したい | Set |
順序付きのリスト | Array |
集合演算したい | Set |
UIや順序重視の操作 | Array |