JavaScript Sets
Table of Contents
JavaScript Set and Its Methods:
Introduction to Sets in JavaScript
A Set in JavaScript is a collection of unique values. Unlike arrays, a Set automatically removes duplicate entries. It can hold any type of value—primitive or object references.
Key Characteristics
- Unique values: A Set ensures that all elements are unique.
- Iterable: Sets are iterable, meaning you can loop over their values.
- No duplicates: Any attempt to add duplicate values is ignored.
- Unordered: Elements in a Set are not indexed and do not follow a specific order.
Example
let mySet = new Set([1, 2, 3, 4, 4, 5]);
console.log(mySet); // Output: Set {1, 2, 3, 4, 5}
In this example, the duplicate 4 is removed automatically.
Creating Sets
You can create a Set using the Set constructor, either with or without an iterable (like an array) as its input.
Creating an Empty Set
let emptySet = new Set();
Creating a Set from an Array
let setFromArray = new Set([10, 20, 30, 40]);
console.log(setFromArray); // Output: Set {10, 20, 30, 40}
Set Methods
JavaScript provides several methods for working with Sets, allowing you to manipulate and inspect the collection.
add()
The add() method adds a new element to the Set. If the element already exists, it is not added again.
Example:
let numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // Duplicate, won't be added
console.log(numbers); // Output: Set {1, 2}
delete()
The delete() method removes a specific element from the Set and returns true if the element was successfully removed.
Example:
let colors = new Set(['Red', 'Green', 'Blue']);
colors.delete('Green');
console.log(colors); // Output: Set { 'Red', 'Blue' }
has()
The has() method checks if a particular element exists in the Set. It returns true if the element is found, otherwise false.
Example:
let cities = new Set(['New York', 'London']);
console.log(cities.has('London')); // Output: true
console.log(cities.has('Paris')); // Output: false
clear()
The clear() method removes all elements from the Set, making it empty.
Example:
let fruits = new Set(['Apple', 'Banana']);
fruits.clear();
console.log(fruits); // Output: Set {}
size
The size property returns the number of elements in the Set.
Example:
let fruits = new Set(['Apple', 'Banana', 'Mango']);
console.log(fruits.size); // Output: 3
Set Iteration Methods
Sets can be iterated over in various ways, thanks to the iterable nature of this data structure.
forEach()
The forEach() method executes a provided function once for each value in the Set.
Example:
let languages = new Set(['JavaScript', 'Python', 'C++']);
languages.forEach(lang => console.log(lang));
// Output:
// JavaScript
// Python
// C++
values()
The values() method returns a new iterator object containing all the values in the Set. It’s essentially the same as the keys() method, as Sets do not have keys.
Example:
let numbers = new Set([1, 2, 3]);
let valuesIterator = numbers.values();
console.log(valuesIterator.next().value); // Output: 1
entries()
The entries() method returns an iterator object with key-value pairs, where both the key and the value are the same for each entry.
Example:
let set = new Set(['a', 'b', 'c']);
for (let entry of set.entries()) {
console.log(entry);
}
// Output:
// ['a', 'a']
// ['b', 'b']
// ['c', 'c']
keys()
The keys() method returns the same iterator as values(). Since Sets don’t have keys, the method returns the values of the Set.
Example:
let set = new Set([100, 200, 300]);
for (let key of set.keys()) {
console.log(key); // Output: 100, 200, 300
}
Set Operations
While JavaScript’s Set object doesn’t include methods like union, intersection, or difference by default, you can implement them manually using the Set’s methods.
Union
To create a union of two sets (all unique elements from both sets), use the add() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let unionSet = new Set([...setA, ...setB]);
console.log(unionSet); // Output: Set {1, 2, 3, 4, 5}
Intersection
To create an intersection of two sets (common elements in both sets), use the has() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);
let intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Output: Set {2, 3}
Difference
To find the difference of two sets (elements in set A but not in set B), use the has() method.
Example:
let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);
let difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Output: Set {1, 2}
WeakSet (Special Type of Set)
A WeakSet is a special type of Set that only holds objects and does not prevent them from being garbage collected. WeakSets have the following differences from Sets:
- Only accepts objects (not primitive values).
- WeakSet elements are not enumerable and cannot be iterated.
- Methods include add(), delete(), and has(), but not size, clear(), or iteration methods.
Example:
let ws = new WeakSet();
let obj = {};
ws.add(obj);
console.log(ws.has(obj)); // Output: true
Summary
- Sets in JavaScript are an efficient way to store unique values.
- They offer several useful methods to manipulate and retrieve data, making them an excellent tool when you need collections with no duplicates.
- Additionally, you can manually implement set operations such as union, intersection, and difference.