In JavaScript, there is a data structure called a Set that is used to store and handle unique values. Sets hold unique values and do not allow duplicate values. In this article, we will show how JavaScript Sets are used and how they work.
Creating a Set
Sets are defined by creating a new Set object:
// Creating an empty Set
let mySet = new Set();
// Creating a Set with values
let mySet = new Set([1, 2, 3, 4, 5]);
Adding and Removing Values
To add a value to a Set, we use the add()
method:
mySet.add(6);
To remove a value from a Set, we use the delete()
method:
mySet.delete(4);
Checking for Value Existence
To check if a specific value exists in the Set, we use the has()
method:
if (mySet.has(3)) {
console.log('The Set contains the value 3.');
} else {
console.log('The Set does not contain the value 3.');
}
Getting the Size of a Set
To get the size of the Set, i.e., the number of unique values it contains, we use the size
property:
console.log('Set size:', mySet.size);
Iterating Over a Set
To iterate through the contents of a Set, we use the forEach()
method:
mySet.forEach((value) => {
console.log(value);
});
Example Usage
The following example uses a Set to filter out duplicate values from an array:
let myArray = [1, 2, 2, 3, 4, 4, 5];
let uniqueValues = new Set(myArray);
console.log([...uniqueValues]); // [1, 2, 3, 4, 5]
JavaScript Sets are a powerful and useful tool for working with unique values. This data structure is especially helpful for removing duplicate values.