6
6

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 3 years have passed since last update.

JavaScript: Set(🦊,🐱,🐶)とSet(🐱,🐶,🐹)の共通要素Set(🐱,🐶)を求める方法

Last updated at Posted at 2020-07-24

この投稿では、JavaScriptの2つのSetから、その共通要素(intersection)を調べる方法を紹介します。

2つのSetの共通要素を調べる方法

const a = new Set(['🦊', '🐱', '🐶'])
const b = new Set(['🐱', '🐶', '🐹'])
const intersection = new Set([...a].filter(x => b.has(x)))
console.log(intersection)
//=> Set { '🐱', '🐶' }

このnew Set([...a].filter(x => b.has(x)))の部分が共通要素のSetを作るコードです。やっていることは、1つ目のセットの配列を作った上で、filterメソッドでその要素ひとつひとつに対して「2つ目のセットの要素かどうか」の基準で絞り込み、最終的に絞り込み結果の配列をSetに戻しているだけです。

汎用的に使う場合は関数化しておくといいかもしれません。

function intersectionOf(a, b) {
  return new Set([...a].filter(x => b.has(x)))
}
6
6
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?