8
4

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 1 year has passed since last update.

【Javascript】配列内の重複要素を削除する

Last updated at Posted at 2022-04-03

はじめに

配列内の重複要素を削除する方法を備忘録として残しておきます。

indexOfを使用する

const array = [1, 2, 3, 4, 5, 1, 2, 1, 1, 4, 6, 7, 3]

const unique = array.filter((item, index) => {
  return array.indexOf(item) === index
})

console.log(unique); //=> [1, 2, 3, 4, 5, 6, 7] 

new Setを使用する

const array = [1, 2, 3, 4, 5, 1, 2, 1, 1, 4, 6, 7, 3]

const unique = [... new Set(array)]

console.log(unique); //=> [1, 2, 3, 4, 5, 6, 7] 

どちらを使うべきか?

結論 new Setを使う。
以下の記事にもあるように、どちらでも重複要素を削除することは可能だが、fileterは配列内の要素数が多くなればなるほど処理が重くなるので、基本的にはnew Setで事足りるかなという印象です。

おわりに

もっと良い方法があれば教えていただけると幸いです。

8
4
2

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
8
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?