In JavaScript, a Set is a built-in object that allows you to store a collection of unique values. Sets are part of ES6 (ECMAScript 2015) and are widely used for managing unique data efficiently. Unlike arrays, Sets automatically filter duplicate values, making them ideal for scenarios where uniqueness is essential.
What Is a JavaScript Set?
A Set is a collection of unique values where:
- Values can be of any data type (primitive or object).
- Duplicate values are automatically ignored.
- The order of elements in a Set is based on insertion order.
Creating a Set
You can create a new Set using the Set constructor.
// Create an empty Set
const mySet = new Set();
// Create a Set with initial values
const fruits = new Set(['apple', 'banana', 'orange']);
console.log(fruits); // Output: Set(3) { 'apple', 'banana', 'orange' }
Key Characteristics of Sets
No Duplicates: Sets automatically discard duplicate entries.
const numbers = new Set([1, 2, 2, 3]);
console.log(numbers); // Output: Set(3) { 1, 2, 3 }
Dynamic Size: Sets are dynamic; you can add or remove elements at any time.
Efficient Lookup: Checking for the presence of a value is faster in a Set compared to arrays
Basic Set Operations
1. Adding Elements
Use the add() method to add elements to a Set.
const mySet = new Set();
mySet.add(10);
mySet.add(20);
mySet.add(10); // Duplicate, ignored
console.log(mySet); // Output: Set(2) { 10, 20 }
2. Removing Elements
Use the delete() method to remove specific elements.
const mySet = new Set([1, 2, 3]);
mySet.delete(2);
console.log(mySet); // Output: Set(2) { 1, 3 }
3. Checking for Elements
Use the has() method to check if an element exists.
const mySet = new Set(['apple', 'banana']);
console.log(mySet.has('apple')); // Output: true
console.log(mySet.has('orange')); // Output: false
4. Clearing All Elements
Use the clear() method to remove all elements from a Set.
const mySet = new Set([1, 2, 3]);
mySet.clear();
console.log(mySet); // Output: Set(0) {}
5. Finding the Size
Use the size property to determine the number of elements.
const mySet = new Set(['a', 'b', 'c']);
console.log(mySet.size); // Output: 3
Iterating Over Sets
You can iterate through the elements of a Set using various methods:
1. for…of Loop
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
// Output:
// red
// green
// blue
2. forEach Method
const numbers = new Set([10, 20, 30]);
numbers.forEach((value) => {
console.log(value);
});
// Output:
// 10
// 20
// 30
Working with Sets and Arrays
Convert a Set to an Array
Use the spread operator . . . or Array.from().
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray); // Output: [1, 2, 3]
Convert an Array to a Set
Use the Set constructor to eliminate duplicates.
const myArray = [1, 2, 2, 3];
const uniqueSet = new Set(myArray);
console.log(uniqueSet); // Output: Set(3) { 1, 2, 3 }
Common Use Cases for Sets
Remove Duplicates from an Array
const duplicates = [1, 2, 2, 3, 4, 4];
const unique = [...new Set(duplicates)];
console.log(unique); // Output: [1, 2, 3, 4]
Check Membership Efficiently
const allowedUsers = new Set(['Alice', 'Bob']);
console.log(allowedUsers.has('Alice')); // Output: true
console.log(allowedUsers.has('Eve')); // Output: false
Mathematical Operations
Perform operations like union, intersection and difference using Sets.
Union: Combine two sets.
const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const union = new Set([...setA, ...setB]);
console.log(union); // Output: Set(5) { 1, 2, 3, 4, 5 }
Intersection: Find common elements.
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Output: Set(1) { 3 }
Difference: Elements in setA but not in setB.
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Output: Set(2) { 1, 2 }
Limitations of Sets
- No Indexing: Sets do not support indexing like arrays.
- Primitive Type Equality: Two objects with the same content are treated as distinct.
const set = new Set();
set.add({ key: 'value' });
set.add({ key: 'value' }); // Considered unique
console.log(set.size); // Output: 2