Introduction
In JavaScript, a Set
is a collection of unique values. It can store any type of value, whether primitive values or object references. Here are some key features and functionalities of the Set
object in JavaScript:
Key Features of Set In JS
- Unique Values: A
Set
can only contain unique values. If you try to add a value that already exists in theSet
, it will be ignored. - Iterability:
Set
objects are iterable, meaning you can loop through the elements in insertion order. - Type of Elements:
Set
can store any type of elements, including objects, strings, numbers, and more.
Creating a Set In JS
For creating a new Set
, we use the set
constructor
let set = new Set();
JavaScriptWe can also initialize Set
with an array of values:
let set = new Set([1,2,3,4,5]);
JavaScriptBasic Operations of Set In JS
Adding Elements
For adding elements to a set , we can use the add method
let set = new Set();
set.add(1);//Output will be Set(1) { 1 }
set.add(2); //Output will be Set(2) { 1 , 2 }
JavaScriptTherefore, if duplicate value , it will be ignored.
set.add(1); // Set still contains {1, 2}
JavaScriptChecking for Values
To check if a Set
contains a specific value, use the has
method:
console.log(set.has(1)); // Output: true
console.log(set.has(3)); // Output: false
JavaScriptDeleting Elements
To delete an element from a Set
, use the delete
method:
set.delete(1);
console.log(set.has(1)); // Output: false
JavaScriptClearing the Set
To remove all elements from a Set
, use the clear
method:
set.clear();
console.log(set.size); // Output: 0
JavaScriptIterating over a Set
Sets maintain the order of insertion, which makes iteration straightforward. You can use various methods to iterate over the elements of a Set
:
Using for...of
for (let value of set) {
console.log(value);
}
JavaScriptUsing forEach
set.forEach(value => {
console.log(value);
});
JavaScriptSet vs Array
Although all do the same work of holding a group of values, there are advantages to using sets:
Uniqueness: Each value being unique is automatically enforced with a set.
Performance: Checking the existence of a value is generally faster in a Set versus an array.
Order of Elements: In sets, an element maintains its insertion order. There are applications of this fact in various algorithms.
Advanced Usage
Removing Duplicates from an Array
One of the common uses of a Set
is to remove duplicates from an array:
let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
JavaScriptPerforming Set Operations
Sets support typical set operations like union, intersection, and difference:
- Union: Combining two sets to include all unique elements from both sets.
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let union = new Set([...setA, ...setB]); // {1, 2, 3, 4, 5}
JavaScript- Difference: Getting the elements that are present in the first set but not in the second.
let difference = new Set([...setA].filter(x => !setB.has(x))); // {1, 2}
JavaScriptCommon Use Cases
Ensuring Uniqueness: Use sets to store unique values, like unique IDs or user inputs.
Filtering: Filter the duplicates out of an array or list by efficaciously removing them.
Set Operations: Allow the calculation of unions, intersections, and differences in sets.
Tracking States: Track states or flags to be unique within the program.
Conclusion
The Set object in JavaScript is a very strong and useful tool for the management of a collection of unique values. Its ease of use, plus performance advantages for certain operations, makes JavaScript developers see its worthiness as an important addition to their toolkits. Understanding and using Set can help developers write cleaner and more efficient code for many use cases.
Frequently Asked Questions
Set
in JavaScript? A JavaScript Set is a collection of values. The value uniqueness makes sure that no two equal values are placed together. The Set order of elements is determined by their insertion sequence and is iterable.
Set
differ from an Array
? While a Set and an Array are two different collections to store values, a Set naturally guarantees uniqueness; that is, no value can come more than once in a Set, while an Array can have repeating values. Other operations, such as finding a particular value, are generally much faster in a Set than in an Array.
Set
? Values are added to a Set using the add method. If a value already exists in the Set, it won’t be added again, so the values are unique.