Javascript sets are a unique way to create objects which can be mutated and contain no duplicates.
A Set in Javascript is a great way to check if a value exists in a specified list of other values. Javascript sets are useful because they are typically faster than something like Array.includes - so they provide an efficient and optimized way of checking if a value exists in a set of other values.
To create a new set, we use the new Set() constructor:
let mySet = new Set();
Basic Operations Of Sets
You can perform a number of operations on sets and they are very easy to understand. Let's take a look
Adding elements to a Set
The add() method is used to add elements to a set:
let mySet = new Set();
mySet.add(5);
console.log(mySet);
// Set(1) {5}
Sets can contain any data type - so you can add objects, numbers, strings, or anything else which you desire.
let mySet = new Set();
mySet.add('five');
console.log(mySet);
// Set(1) {'five'}
If you try to add the same value twice, it will only appear in the set once:
let mySet = new Set();
mySet.add(5);
mySet.add(5);
console.log(mySet);
// Set(1) {5}
Deleting elements from a Set
To delete a single element from a set in Javascript, you can use the delete() method:
let mySet = new Set();
mySet.add(5);
mySet.delete(5);
console.log(mySet);
// Set(0) {}
Deleting all elements from a Set
To delete all elements from a set in Javascript, you can use the clear() method:
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.clear();
console.log(mySet);
// Set(0) {}
Checking for existing values in sets
The has() method is used to search element from Set.
// Create new set with some values
const mySet = new Set(['Rahul', 'Rocky', 'Ramesh', 'Emma'])
// Check if "mySet" contains "Rocky"
mySet.has('Rocky')
// true
// Check if "mySet" contains "Leopold"
mySet.has('Leopold')
// false
Checking the size of a set
To check the size or length of a set, we can't use .length, like we normally would. Instead, the size of a set is found using .size.
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
console.log(mySet.size);
// 3
Sets, keys and values
If you want to find out what values a set contains, there are two methods you can use. Well, it is one method and one alias for the same method. The method is values() and the alias is keys(). Using any of these methods will create an iterator object. This iterator contains all values in the order in which you added them to the set.
When you have this iterator you can iterate over all values one by one. If you are not familiar with iterators and generators. When you work with iterator object, you can go to the next value by calling the next() method. You call this method on the iterator object you created.
// Create new set
const mySet = new Set()
// Add some values
mySet.add('Loki')
mySet.add('Thor')
mySet.add('Freyr')
// Create an iterator object that contains all values
const mySetValues = mySet.values()
// Alternative:
// const mySetValues = mySet.keys()
// Log the value of "mySetValues"
console.log(mySetValues)
// [Set Iterator] { 'Loki', 'Thor', 'Freyr' }
// Log the first value
console.log(mySetValues.next().value)
// 'Loki'
// Log the second value
console.log(mySetValues.next().value)
// 'Thor'
// Log the third value
console.log(mySetValues.next().value)
// 'Freyr'
// Log the fourth value
// There are only three values in the set
// that's why the "value" is now "undefined"
console.log(mySetValues.next().value)
// undefined
Looping over values with for...of loop
If you don't want use the next() method to get the values, you can use for...of loop instead. The for...of loop will help you to loop over the iterator object and get all values one by one automatically.
// Create new set
const mySet = new Set()
// Add some values
mySet.add('Loki')
mySet.add('Thor')
mySet.add('Freyr')
// Create an iterator object that contains all values
const mySetValues = mySet.values()
// Loop over the "mySetValues" iterator object
// and log all values one by one
for (const val of mySetValues) {
console.log(val)
}
// 'Loki'
// 'Thor'
// 'Freyr'
Getting all entries in a set
Aside to the values() and keys() methods, you can also access all values inside a set with entries() method. Similarly to values() and keys(), this method also creates an iterator object containing all entries. You can then iterate over this object using either next() method or for...of loop.
// Create new set
const mySet = new Set()
// Add some values
mySet.add('MSFT')
mySet.add('AAPL')
mySet.add('BABA')
mySet.add('ADBE')
mySet.add('DELL')
// Create an iterator object that contains all entries (values)
const mySetEntries = mySet.entries()
// Loop over the "mySetValues" iterator object
// and log all values one by one
for (const entry of mySetEntries) {
console.log(entry)
}
// Output:
// [ 'MSFT', 'MSFT' ]
// [ 'AAPL', 'AAPL' ]
// [ 'BABA', 'BABA' ]
// [ 'ADBE', 'ADBE' ]
// [ 'DELL', 'DELL' ]
// Or using next() method
// Log the first value
console.log(mySetEntries.next().value)
// [ 'MSFT', 'MSFT' ]
// Log the second value
console.log(mySetEntries.next().value)
// [ 'AAPL', 'AAPL' ]
// Log the third value
console.log(mySetEntries.next().value)
// [ 'BABA', 'BABA' ]
// Log the fourth value
console.log(mySetEntries.next().value)
// [ 'ADBE', 'ADBE' ]
When you use the entries() method the format for each entry will be [ key, value ]. What may surprise you is that the key and value in this entry array will be the same. You could see this on the example above. Don't worry about this. This is how the entries() method was implemented in JavaScript.
Iterating over a Set
Sets themselves are able to be looped through with a simple for loop:
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
for(let x of mySet) {
console.log(x);
}
// 5
// 10
// 20
However, sets also come with the forEach() method attached, so you can use that too. Typically for loops are faster, though:
let mySet = new Set();
mySet.add(5);
mySet.add(10);
mySet.add(20);
mySet.forEach(() => {
console.log(x);
}
// 5
// 10
// 20
I hope this tutorial made it easier for you to understand what sets in JavaScript are, how they work and, most importantly, how to use them.
0 Comments