JavaScript
array
reduce
unique

[Javascript] 配列の重複を取り出す方法

More than 1 year has passed since last update.

Javascriptでは標準でuniquedistinct関数がないので、配列の重複を取り出すいくつかの方法を紹介します。

Array.prototype.reduceを使う方法

const animals = ["cat", "cat", "dog", "mouse", "dog"];

const distinctAnimals = animals.reduce(
  (distinct, animal) =>
    (distinct.indexOf(animal) !== -1) ? distinct : [...distinct, animal]
  , []
)

console.log(distinctAnimals)

// ["cat", "dog", "mouse"]

reduceの初期値を空の配列[]にし、重複がなければ、配列に入れていていく方法です。

Array.prototype.filterを使う方法

const animals = ["cat", "cat", "dog", "mouse", "dog"];

const distinctAnimals = animals.filter((animal, index, array) => {
    return array.indexOf(animal) === index;
});

console.log(distinctAnimals);

// ["cat", "dog", "mouse"]

ES6のSetを使う方法

const animals = ["cat", "cat", "dog", "mouse", "dog"];

const distinctAnimals = [...new Set(animals)];

console.log(distinctAnimals);

// ["cat", "dog", "mouse"]