JavaScript Sets
A set is a built-in object that represents a collection of unique values.
Sets are implemented as collections of values, where each value is unique and can occur only once within the set.
This means that you can use a set to store a collection of unique values without worrying about duplicates.
Here's an basic example of a set:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(2); // this value is already in the set, so it will not be added
console.log(mySet.size); // outputs 3
mySet.delete(2); // removes the value 2 from the set
console.log(mySet.has(2)); // outputs false, because 2 is no longer in the set
for (let value of mySet) {
console.log(value); // outputs 1, 3
}
In this example:
- We create a new set called
mySet
using theSet()
constructor. We then add four values to the set, including the value 2 twice. - Since sets only store unique values, the second instance of 2 is ignored.
- We then output the
size
of the set using the size property, which is 3.
Next:
- We remove the value 2 from the set using the
delete()
method. - We then use the
has()
method to check if the value 2 is still in the set (it's not). - finally we loop over the remaining values in the set using a
for..of
loop and log each value to the console.
Essential Set Methods
Let's take a look at some of the most important methods of the Set
object.
Method | Description |
---|---|
new Set() | Creates a new Set |
add() | Adds a new element to the Set |
delete() | Removes an element from a Set |
has() | Returns true if a value exists in the Set |
forEach() | Invokes a callback for each element in the Set |
values() | Returns an iterator with all the values in a Set |
Property | Description |
size | Returns the number of elements in a Set |
How to create a Set
You can create a set in JavaScript using the Set()
constructor.
Here's an example:
const mySet = new Set();
In this example:
- We create a new set called
mySet
.
You can also pass an iterable object to the Set()
constructor to create a set with initial values.
As an example:
const mySet = new Set([1, 2, 3]);
In this example:
- We create a new set called
mySet
with the initial values of 1, 2, and 3.
The add()
Method
The add()
method is used to add elements to a Set
.
The add()
method returns the Set
object, so you can chain multiple add()
calls together.
As an example:
const mySet = new Set([1, 2, 3]);
mySet.add(4).add(5);
console.log(mySet); // Output: Set { 1, 2, 3, 4, 5 }
In this example:
- We first create a new
Set
object mySet with three elements. - Then we use the add() method to add the elements 4 and 5 to the
Set
. - Finally, we log the
Set
object to the console to verify that the elements were added successfully.
The add()
method only adds an element to the Set
if it doesn't already exist in the Set
. If the element already exists, the Set
remains unchanged.
You can also add multiple values to a set
at once by passing an iterable object to the add()
method.
As an example:
mySet.add(4).add(5).add(6);
This will add the values 4, 5, and 6 to the set
.
The delete()
Method
The delete()
method is used to remove elements from a Set
.
The delete()
method returns a boolean value indicating whether or not the element was successfully removed from the Set
.
As an example:
const mySet = new Set([1, 2, 3, 4]);
mySet.delete(3);
console.log(mySet); // Output: Set { 1, 2, 4 }
In this example:
- We first create a new
Set
object mySet with four elements. - Then we use the
delete()
method to remove the element 3 from theSet
. - Finally, we log the
Set
object to the console to verify that the element was removed successfully.
If the element doesn't exist in the Set
, the delete()
method will return false and the Set
remains unchanged.
The has()
Method
The has()
method is used to check if a Set
contains a specific element.
The has()
method returns a boolean value indicating whether or not the Set
contains the specified element.
As an example:
const mySet = new Set([1, 2, 3, 4]);
console.log(mySet.has(3)); // Output: true
console.log(mySet.has(5)); // Output: false
In this example:
- We first create a new
Set
object mySet with four elements. - Then we use the
has()
method to check if theSet
contains the elements 3 and 5. - Finally, we log the boolean values to the console to verify whether or not the
Set
contains the specified elements.
The has()
method works with any type of value, including objects and arrays, as long as they are unique values.
The size
Method
The size
property is used to get the number of elements in a Set
.
The size
property returns an integer value representing the number of elements in the Set
.
As an example:
const mySet = new Set([1, 2, 3, 4]);
console.log(mySet.size); // Output: 4
In this example:
- We first create a new
Set
object mySet with four elements. - Then we use the size property to get the number of elements in the
Set
. - Finally, we log the integer value to the console to verify the number of elements in the
Set
.
The size property is a read-only property and cannot be set directly. The size of a Set
can only be changed by adding or removing elements from the Set
.
Iterating set using for...of
loop
You can use a for...of
loop to iterate over a Set
in JavaScript.
As an example:
const mySet = new Set([1, 2, 3]);
for (let value of mySet) {
console.log(value);
}
// output:
// 1
// 2
// 3
In this example:
- We first create a new
Set
object mySet with four elements. - Then we use a
for...of
loop to iterate over theSet
and log each value to the console.
Converting a set
to an array
You can convert a Set
to an array using the Array.from()
method or the spread syntax ...
.
As an example:
const mySet = new Set([1, 2, 3, 4]);
const myArray = Array.from(mySet);
console.log(myArray); // Output: [1, 2, 3, 4]
In this example:
- We first create a new
Set
object mySet with four elements. - Then we use the Array.from() method to convert the
Set
to an array. - Finally, we log the array to the console to verify the conversion.
Here's another example of using the spread syntax ...
to convert a Set
to an array:
const mySet = new Set([1, 2, 3, 4]);
const myArray = [...mySet];
console.log(myArray); // Output: [1, 2, 3, 4]
In this example:
- We use the spread syntax ... to convert the
Set
to an array. - This syntax expands the elements of the
Set
into a new array. - Finally, we log the array to the console to verify the conversion.
Creating a set
from an array
You can create a new set
from an array using the spread operator (...
) and the Set()
constructor.
As an example:
const myArray = [1, 2, 3];
const mySet = new Set([...myArray]);
console.log(mySet); // output: Set {1, 2, 3}
Using sets to filter out duplicates from an array Sets can be useful for filtering out duplicate values from an array.
As an example:
const myArray = [1, 2, 3, 2, 1];
const mySet = new Set(myArray);
const uniqueArray = [...mySet];
console.log(uniqueArray); // output: [1, 2, 3]
In this example:
- We create a new set
mySet
from the original arraymyArray
, which filters out the duplicate values. - We then convert the set back to an array using the spread operator
...
, resulting in an arrayuniqueArray
with only the unique values from the original array.