LoginSignup
1
1

`Set<string>` と `string[]` の違いについて

Posted at

はじめに

JavaScriptやTypeScriptでデータを管理する際に、Set<string>string[] という二つの選択肢があります。それぞれの違いと使用方法について詳しく解説します。

Set<string>

特徴

  • 重複を許さない: Setは重複する値を持つことができません。同じ値が追加されると、元の値がそのまま保持され、新しい値は追加されません。
  • 順序が保証されない: Setは要素の挿入順序を保証しません。
  • メソッド: Setadd, delete, has, clearなどのメソッドを持ちます。

使用例

重複する可能性があるデータを一意に保ちたい場合に便利です。

const userUids = new Set<string>();

// 値を追加
userUids.add('uid1');
userUids.add('uid2');
userUids.add('uid1'); // 重複は無視される

// 値の存在をチェック
if (userUids.has('uid1')) {
  console.log('uid1 exists');
}

// 値を削除
userUids.delete('uid1');

// 全ての値をループ
for (const uid of userUids) {
  console.log(uid);
}

string[]

特徴

  • 重複を許す: 配列は重複する値を持つことができます。同じ値が複数回追加されると、すべての値が保持されます。
  • 順序が保証される: 配列は要素の挿入順序を保持します。
  • メソッド: 配列はpush, pop, shift, unshift, splice, indexOfなどのメソッドを持ちます。

使用例

順序が重要である場合や、重複するデータを保持する必要がある場合に便利です。

const userUids: string[] = [];

// 値を追加
userUids.push('uid1');
userUids.push('uid2');
userUids.push('uid1'); // 重複が許される

// 値の存在をチェック
if (userUids.indexOf('uid1') !== -1) {
  console.log('uid1 exists');
}

// 値を削除
const index = userUids.indexOf('uid1');
if (index !== -1) {
  userUids.splice(index, 1);
}

// 全ての値をループ
for (const uid of userUids) {
  console.log(uid);
}

選択の基準

  • 重複を避けたい: Set<string>
  • 順序を保持したい: string[]
  • 重複する値を保持したい: string[]

これらの点を考慮して、データの性質や要件に応じて適切なデータ構造を選択しましょう。

1
1
1

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
1
1