Member-only story
A complete reference to Set in Javascript
5 min readAug 19, 2024
Set
A Set
is a special type of object in JavaScript that allows you to store unique values of any type, whether primitive values or object references. The duplicate values will be removed automatically that you attempt to add.
For example, if you have an array with duplicate values, you can easily convert it into a Set
to filter out the duplicates.
const numbers = [1, 2, 3, 4, 4, 5, 5, 6];
const uniqueNumbers = new Set(numbers);
console.log(uniqueNumbers); // Output: Set(6) { 1, 2, 3, 4, 5, 6 }
We can also create a Set
using the Set
constructor.
var setObj = new Set(); // creates a empty set
setObj.add(1);
setObj.add(2);
console.log(setObj); // Set(2) {1, 2}
setObj.add(1); // duplicate value will not be added.
console.log(setObj); // Set(2) {1, 2}
When Should You Use the Set
Data Structure? 🤔
The Set
data structure is ideal for scenarios where you need to store a collection of unique items. Common use cases include:
- Removing duplicates from arrays: Convert an array to a
Set
and back to remove any duplicate values. - Efficient lookups: Checking if a value exists in a
Set
is generally faster than in an array, especially for large datasets.