Introduction to Sets
If you‘re an experienced JavaScript developer, you‘ve likely come across situations where you needed a data structure to store unique values.
Handling duplicates elegantly in arrays or objects can get messy. That‘s where sets come in.
Sets are collections of unique, unsorted values.
The values in a set can be either primitive data types like strings, numbers, booleans, or object references.
Sets have some killer features:
- Store only unique values – automatically handle duplicates
- Super fast lookups, inserts and deletes
- Methods like add, delete, has, clear that make working with data easy
- Sorted insertion order
- Perfect for mathematical set operations like unions, intersections etc.
Let‘s see how to create a set:
// Create empty set
const letters = new Set();
// Initialize with values
const numbers = new Set([1, 2, 3]);
You can also create a set from any iterable object like an array:
const array = [1, 2, 2, 3, 4];
const unique = new Set(array); // {1, 2, 3, 4}
This removes any duplicates, leaving us with a set of unique values. Sweet!
Alright, now that you know what sets are, let‘s dig into the useful properties and methods you can use.
Handy Set Methods and Properties
size
To get the number of elements in a set, use the size property:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
console.log(letters.size); // 3
Keep in mind size reflects the number of unique values.
has
To check if a value exists in a set, use the has method:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
console.log(letters.has(‘b‘)); // true
console.log(letters.has(‘d‘)); // false
has() lets you check for membership very quickly.
add
To add a new element to a set, use the add method:
const letters = new Set([‘a‘, ‘b‘]);
letters.add(‘c‘);
letters.add(‘a‘); // Won‘t actually add since ‘a‘ exists
add() is a great way to append new values.
delete
To remove an element from a set, use the delete method:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
letters.delete(‘b‘); // letters is now [‘a‘, ‘c‘]
delete doesn‘t throw an error if the value doesn‘t exist.
clear
To empty an entire set at once, use the clear method:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
letters.clear(); // letters is now empty
keys/values/entries
Since sets only contain unique values, the keys, values, and entries iterators all return the values:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
const iterator1 = letters.keys();
const iterator2 = letters.values();
const iterator3 = letters.entries();
iterator1.next().value // ‘a‘
iterator2.next().value // ‘a‘
iterator3.next().value // [‘a‘, ‘a‘]
These iterators let you loop through sets in different ways.
forEach
To loop through a set and execute a callback on each value, use the forEach method:
const letters = new Set([‘a‘, ‘b‘, ‘c‘]);
letters.forEach(letter => {
console.log(letter);
})
// Logs ‘a‘, ‘b‘, ‘c‘
forEach is super handy for general looping.
Alright, now you know how to manipulate sets and their data. Let‘s look at some real-world use cases where sets shine.
Real-World Set Usage
Removing Duplicates
Removing duplicate values from arrays is a common problem. With sets, it‘s trivial:
const array = [1, 2, 3, 3, 4];
const unique = [...new Set(array)]; // [1, 2, 3, 4]
We create a set from the array, which filters out the dupes. Spreading it back into an array gives us the de-duped result.
You can also create a set from a string to get unique characters:
const sentence = "Hello World hello";
const uniqueChars = [...new Set(sentence)]; // ["H", "e", "l", "o", " ", "W", "r", "d"]
No more annoying nested loops to handle duplicates!
Union and Intersection
Sets shine when performing mathematical set operations like unions, intersections, differences etc.
For example, to get the union of two sets:
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
const union = new Set([...setA, ...setB]); // {1, 2, 3, 4}
We can spread two sets into a new set to get the union with unique values.
For intersection, we can use filter():
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
const intersection = new Set([...setA].filter(x => setB.has(x))); // {2, 3}
Other operations like differences and subsets are also possible.
Validating Data
You can use a set as an allowlist or denylist – quickly validate if some data is allowed/denied:
// Allowlist of domains
const validDomains = new Set(["gmail.com", "yahoo.com", "msn.com"]);
function isValidEmail(email) {
return validDomains.has(email.split("@")[1]);
}
isValidEmail("[email protected]"); // true
isValidEmail("[email protected]"); // false
Blazing fast lookups to validate data!
Removing List Duplicates
For nested lists with object duplicates, convert each object to a primitive (like a string) and use a set:
const users = [
{ name: "John", age: 20 },
{ name: "Sarah", age: 21 },
{ name: "John", age: 20 }
];
const uniqueUsers = [...new Set(users.map(u => JSON.stringify(u)))]
.map(u => JSON.parse(u));
// [{ name: "John", age: 20 }, { name: "Sarah", age: 21 }]
By stringifying objects, we can reliably remove duplicates.
Cache
Sets make simple, fast caches. Just add() values and check if they exist with has().
Better performance than arrays/objects:
const cache = new Set();
// Add cached values
cache.add("Hello");
cache.add("World");
// Check if value is cached
cache.has("Hello"); // true
Sets have tons of cool applications if you‘re creative:Bloom filters, pathfinding, image processing…the possibilities are endless!
Wrapping Up: Master JavaScript Sets
So there you have it – a comprehensive guide to understanding sets in JavaScript.
To recap:
- Sets store unique values of any type
- Useful methods like
add,delete,has,clear - Fast lookups, inserts and deletes
- Insertion order is maintained
- Great for removing duplicates and mathematical set operations
- Possible applications like caching, data validation, removing duplicates etc.
I hope you now feel empowered to start using sets in your own apps! Let me know if you have any other creative set use cases.
Sets might seem simple at first, but they open up a whole new world of programming techniques. Adding them to your JavaScript toolbox will level up your skills.
Thanks for reading! Please share this guide if you found it helpful.