24
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-07-11

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"]
24
21
6

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
24
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?