Set.prototype.symmetricDifference()
Baseline
2024
Newly available
Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
symmetricDifference() は Set インスタンスのメソッドで、集合を受け取り、この Set と与えられた集合のどちらかにあるが、両方にはない要素の入った新しい Set を返します。
構文
symmetricDifference(other)
引数
返値
新しい Set オブジェクトで、この Set と other の集合のどちらかにあるものの、両方にはない要素が入ったものです。
解説
数学的な記法では、対称差分 (symmetric difference) は次のように定義されます。
ベン図を使うとこうなります。
symmetricDifference() は、Set 風オブジェクトを other 引数として受け入れます。this は、ユーザーコードを呼び出すことなく、this オブジェクトに格納されているデータに直接アクセスするため、実際の Set インスタンスであることが要求されます。次に、other の keys() メソッドを呼び出して繰り返し処理を行い、this に存在し、other に存在しないすべての要素と、other に存在し、this に存在しないすべての要素をすべて含む新しい Set を構築します。
返される Set 内の要素の順序は、まず this の要素、次に other の要素となります。
例
>symmetricDifference() の使用
次の例では、偶数(10 未満)と完全平方(10 未満)の集合の対称差分を計算します。結果は、完全平方または偶数のどちらかで、両方にはない数の集合となります。
const evens = new Set([2, 4, 6, 8]);
const squares = new Set([1, 4, 9]);
console.log(evens.symmetricDifference(squares)); // Set(5) { 2, 6, 8, 1, 9 }
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-set.prototype.symmetricdifference> |
ブラウザーの互換性
Loading…