Sets are a powerful data structure introduced in ES6 (ECMAScript 2015) that store unique values. Unlike arrays, Sets ensure that no element appears more than once, making them ideal for scenarios where you need to eliminate duplicates or check for membership efficiently.
There are two primary ways to create Sets:
Set
Constructor:
const colors = new Set(["red", "green", "blue", "green"]); // "green" is ignored
console.log(colors); // Output: Set(3) {"red", "green", "blue"}
...
) with an Iterable:=
const numbers = new Set([1, 2, 3, 3]);
const uniqueNumbers = new Set([...numbers]); // Spread syntax expands the array
console.log(uniqueNumbers); // Output: Set(3) {1, 2, 3}
add(value)
: Inserts a new value into the Set. If the value already exists, nothing happens.
delete(value)
: Removes a specific value from the Set, returning true
if successful and false
otherwise.
const fruits = new Set(["apple", "banana", "orange"]);
fruits.add("mango");
console.log(fruits); // Output: Set(4) {"apple", "banana", "orange", "mango"}
fruits.delete("banana");
console.log(fruits); // Output: Set(3) {"apple", "orange", "mango"}
has(value)
: Returns true
if the Set contains the specified value, and false
otherwise.
const vegetables = new Set(["carrot", "potato", "tomato"]);
console.log(vegetables.has("carrot")); // Output: true
console.log(vegetables.has("cauliflower")); // Output: false
size
: Returns the number of elements currently present in the Set.
const countries = new Set(["India", "USA", "China", "India"]);
console.log(countries.size); // Output: 3 (duplicates are not counted)
clear()
: Removes all elements from the Set.
forEach(callback)
: Executes a provided function for each element in the Set.
const animals = new Set(["dog", "cat", "rabbit"]);
animals.clear(); // Set becomes empty
animals.add("lion").add("elephant");
animals.forEach(animal => console.log(animal));
// Output: lion (order might vary based on implementation)
// elephant (order might vary based on implementation)
Sets are iterable, meaning you can use for...of
loops or the spread syntax (...
) to access elements.
(intersection
): Although not a built-in method, you can create a helper function to find the common elements between two Sets:
function intersection(set1, set2) {
const result = new Set();
for (const value of set1) {
if (set2.has(value)) {
result.add(value);
}
}
return result;
}
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 3, 5, 6]);
const commonElements = intersection(setA, setB);
console.log(commonElements); // Output: Set(2) {2, 3}
difference
):Similar to the intersection
function, we can create a helper function to find elements present in one Set but not in another:
function difference(set1, set2) {
const result = new Set();
for (const value of set1) {
if (!set2.has(value)) {
result.add(value);
}
}
return result;
}
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 3, 5, 6]);
const distinctElementsInA = difference(setA, setB);
console.log(distinctElementsInA); // Output: Set(2) {1, 4}
union
):To combine elements from two Sets, we can create a function that merges them while keeping unique values:
function union(set1, set2) {
const result = new Set([...set1, ...set2]);
return result;
}
const colorsA = new Set(["red", "green", "blue"]);
const colorsB = new Set(["yellow", "purple", "green"]);
const allColors = union(colorsA, colorsB);
console.log(allColors); // Output: Set(6) {"red", "green", "blue", "yellow", "purple"}
Weak Sets: A special type of Set introduced in ES6 that allows storing only object references as keys. Weak Sets do not prevent garbage collection of the referenced objects, unlike regular Sets. They are useful for scenarios where object references need to be associated with something but shouldn’t prevent those objects from being garbage collected if they’re no longer needed elsewhere. (Note: Weak Sets are a more advanced topic and might not be needed in all situations.)
A common scenario is to eliminate duplicate elements from an array. Sets can efficiently achieve this:
const numbersWithDuplicates = [1, 2, 2, 3, 4, 5, 1];
const uniqueNumbers = new Set(numbersWithDuplicates);
console.log(uniqueNumbers); // Output: Set(5) {1, 2, 3, 4, 5}
Sets excel at quickly determining if a specific value exists within them.
Set operations like union
and difference
are handy for merging or finding distinct elements across Sets.
Sets offer a powerful and versatile data structure in JavaScript. Their ability to store unique values and efficiently perform operations like membership checks, adding/removing elements, and set operations make them a valuable tool for various programming tasks. By understanding the core concepts, creation methods, and advanced techniques covered in this comprehensive guide, you'll be well-equipped to leverage Sets effectively in your JavaScript projects. Happy coding !❤️