Javascriptでは標準でunique
やdistinct
関数がないので、配列の重複を取り出すいくつかの方法を紹介します。
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"]