The intersection() method of the Set object in JavaScript takes another set as an argument and returns a new set containing elements that are present in both the original set and the given set.
The syntax of Set.intersection() method is:
intersection(other)
This intersection() method of Set takes a set and returns a new set containing elements in both this set and the given set.
Parameter | Optional/Required | Description |
---|---|---|
other | required | The set to intersect with the original set. |
Set.intersection() returns value of type Set
.
In JavaScript, we can use the intersection()
method to find the common elements between two sets of numbers.
For example,
setA
with initial values 1, 2, and 3.setB
with initial values 2 and 3.intersection()
method to find the common elements between setA
and setB
, storing the result in intersectionSet
.intersectionSet
to the console using console.log()
.const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3]);
const intersectionSet = setA.intersection(setB);
console.log(intersectionSet);
Set { 2, 3 }
In JavaScript, we can use the intersection()
method to find the common elements between two sets of strings.
For example,
setA
with initial values 'apple', 'banana', and 'cherry'.setB
with initial values 'banana' and 'cherry'.intersection()
method to find the common elements between setA
and setB
, storing the result in intersectionSet
.intersectionSet
to the console using console.log()
.const setA = new Set(['apple', 'banana', 'cherry']);
const setB = new Set(['banana', 'cherry']);
const intersectionSet = setA.intersection(setB);
console.log(intersectionSet);
Set { 'banana', 'cherry' }
In JavaScript, we can use the intersection()
method to find the common elements between two sets of objects.
For example,
setA
with initial objects representing different people.setB
with some overlapping objects.intersection()
method to find the common elements between setA
and setB
, storing the result in intersectionSet
.intersectionSet
to the console using console.log()
.const person1 = { name: 'John' };
const person2 = { name: 'Jane' };
const person3 = { name: 'Doe' };
const setA = new Set([person1, person2]);
const setB = new Set([person2, person3]);
const intersectionSet = setA.intersection(setB);
console.log(intersectionSet);
Set { { name: 'Jane' } }
In this JavaScript tutorial, we learned about intersection() method of Set: the syntax and few working examples with output and detailed explanation for each example.