Set in JavaScript (Live Playground)
In JavaScript, the Set
data structure allows you to store unique values of any type, including primitive values and object references. A Set
object can be used to store and manipulate collections of distinct elements without duplicates. In this tutorial, we will explore the Set
data structure and its methods.
Creating a Set
To create a Set
, use the Set
constructor. You can create an empty set or initialize it with an iterable object, such as an array:
const emptySet = new Set();
const numbers = new Set([1, 2, 3, 4, 5]);
numbers.forEach(num => console.log(num));
Adding Elements
To add elements to a set, use the add
method:
const fruits = new Set();
fruits.add('apple');
fruits.add('banana');
fruits.add('orange');
fruits.add('apple'); // This won't be added since 'apple' is already in the set.
Removing Elements
To remove a specific element from a set, use the delete
method:
fruits.delete('banana'); // Returns true if the element is found and removed, otherwise false.
To remove all elements from a set, use the clear
method:
fruits.clear();
Checking for Elements
To check if a set contains a specific element, use the has
method:
fruits.has('apple'); // Returns true if the element is in the set, otherwise false.
Set Size
To get the number of elements in a set, use the size
property:
fruits.size; // Returns the number of elements in the set.
Iterating Over a Set
You can use the forEach
method or a for...of
loop to iterate over a set:
fruits.forEach(fruit => console.log(fruit));
for (const fruit of fruits) {
console.log(fruit);
}
Conclusion
In this tutorial, we've covered the Set
data structure in JavaScript, which allows you to store unique values efficiently. We've explored how to create a set, add and remove elements, check for elements, determine set size, and iterate over a set. Sets can be particularly useful when you need to store and manipulate collections of distinct elements without duplicates.