Javascript new set
In JavaScript, Set
is a built-in data structure that allows you to store unique values. Here's an overview of how to use it:
Creating a Set
You can create a new Set using the new Set()
constructor:
const mySet = new Set();
Alternatively, you can create a Set from an array or an iterable using the Set()
function:
const mySet = new Set([1, 2, 3, 4, 5]);
Adding elements to a Set
You can add elements to a Set using the add()
method:
mySet.add(6);
mySet.add(7);
Checking if an element is in a Set
You can check if an element is in a Set using the has()
method:
console.log(mySet.has(6)); // true
console.log(mySet.has(8)); // false
Removing elements from a Set
You can remove an element from a Set using the delete()
method:
mySet.delete(6);
Iterating over a Set
You can iterate over a Set using a for...of
loop:
for (const element of mySet) {
console.log(element);
}
Set operations
Sets support various operations, including:
- Union:
mySet.union(otherSet)
returns a new Set containing all elements from both sets. - Intersection:
mySet.intersection(otherSet)
returns a new Set containing all elements common to both sets. - Difference:
mySet.difference(otherSet)
returns a new Set containing all elements inmySet
that are not inotherSet
. - Symmetric difference:
mySet.symmetricDifference(otherSet)
returns a new Set containing all elements that are in eithermySet
orotherSet
, but not in both.
Here's an example:
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
console.log(setA.union(setB)); // Set {1, 2, 3, 4}
console.log(setA.intersection(setB)); // Set {2, 3}
console.log(setA.difference(setB)); // Set {1}
console.log(setA.symmetricDifference(setB)); // Set {1, 4}