0
0

【JavaScript】配列から重複する値自体を削除する方法

Posted at

JavaScriptで、配列から重複する値を削除する方法として、new Set()を用いた方法がありますが、そうではなく、配列から重複する値自体を削除する方法をご紹介します。

日本語がややこしいため、例を出します。

appleとlemonがそれぞれ重複するため、値を削除する
['apple', 'orange', 'apple', 'grape', 'peach', 'lemon', 'lemon']['orange', 'grape', 'peach']

コード

2つ方法をご紹介します。どちらの方法でも、配列から重複する値自体を削除できます。

パターン1

重複する値を抽出した後、ユニークな値を抽出する

const fruits = ['apple', 'orange', 'apple', 'grape', 'peach', 'lemon', 'lemon'];

// 重複する値を抽出
const duplicatedFruits = fruits.filter(
  (fruit, index) => fruits.indexOf(fruit) !== index,
);
// ['apple', 'lemon']

// ユニークな値を抽出
const result = fruits.filter((fruit) => !duplicatedFruits.includes(fruit));
// ['orange', 'grape', 'peach']

パターン2

重複する値を抽出した後、ユニークな値を抽出する

const fruits = ['apple', 'orange', 'apple', 'grape', 'peach', 'lemon', 'lemon'];

// 対象の値が出てくる最初のindexと最後のindexを調べて、同じものを抽出
const result = fruits.filter((fruit) => {
  const firstFruitIndex = fruits.findIndex((f) => f === fruit);
  const lastFruitIndex = fruits.findLastIndex((f) => f === fruit);
  return firstFruitIndex === lastFruitIndex;
});
// ['orange', 'grape', 'peach']

まとめ

配列から重複する値自体を削除する方法をご紹介しました。

どちらの方法もコード量に大きな差はないため、ご自身のコーディングスタイルや、その後の処理との組み合わせやすさなどを考慮して選択してください。

ただし、今回はパフォーマンスを考慮してないため、配列の数が多い場合などは、事前にベンチマークテストを実施することをおすすめします。

最後に

GoQSystemでは一緒に働いてくれる仲間を募集中です!

ご興味がある方は以下リンクよりご確認ください。

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