Language: EN

como-usar-set-en-javascript

The Set Type in JavaScript

Sets in JavaScript are data structures that allow you to store collections of unique values.

This feature makes them useful when we need to ensure the uniqueness of elements (for example, to remove duplicates from an array).

Sets can store any type of data, including primitives like numbers and strings, as well as objects.

Their main characteristics are,

  • Unique values: Duplicates are not allowed. If you try to add an element that already exists, it will simply be ignored.
  • Data types: You can store any type of value, including objects and other Sets.
  • Insertion order: Sets maintain the order of insertion of values.

If you want to learn more about Sets (also called HashSet)
check the Data Structures Course read more ⯈

Creating a Set

To create a Set, we use the Set() constructor:

const mySet = new Set();
console.log(mySet); // Set(0) {}

We can also initialize a Set by passing an Array (or another iterable) as an argument to the constructor:

const numbers = new Set([1, 2, 3, 4, 5]);
console.log(numbers); // Set(5) {1, 2, 3, 4, 5}

If an iterable contains duplicate values, the Set automatically removes them:

const duplicates = new Set([1, 2, 2, 3, 4, 4]);
console.log(duplicates); // Set(4) {1, 2, 3, 4}

Basic Operations

Adding Elements

To add elements to a Set, we use the .add() method. If we try to add an element that already exists, it won’t throw an error, but the Set will ignore the attempt.

const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1); // Ignored

console.log(mySet); // Output: Set { 1, 2 }

Checking Existence of Elements

To check if an element is present in a Set, we use the .has() method, which returns a boolean value:

console.log(mySet.has(1)); // Output: true
console.log(mySet.has(3)); // Output: false

Removing Elements

We can remove elements from a Set using the .delete() method. If the element does not exist, the method will not throw an error, it simply does nothing.

mySet.delete(2);
console.log(mySet); // Output: Set { 1 }

Clearing the Set

If we want to remove all elements from a Set, we can use the .clear() method:

mySet.clear();
console.log(mySet); // Output: Set {}

Getting the Size of the Set

The .size property returns the number of elements in the Set:

const numbers = new Set([1, 2, 3]);
console.log(numbers.size); // 3

Cannot access by index

Unlike arrays, we cannot access elements of a Set by an index. We can only use iteration methods to access its values.

Iterating Over a Set

Sets are iterable, which means we can loop through their elements using a for...of loop, the .forEach() method, or convert them to an array.

Using a for...of Loop

const mySet = new Set(['a', 'b', 'c']);

for (const item of mySet) {
    console.log(item); // Output: a, b, c
}

Using .forEach()

mySet.forEach((value) => {
    console.log(value); // Output: a, b, c
});

Converting to Array

We can convert a Set to an array using the spread operator (...) or the Array.from() method:

const arrayFromSet = [...mySet]; // Using spread operator
const anotherArrayFromSet = Array.from(mySet); // Using Array.from()

console.log(arrayFromSet); // Output: [ 'a', 'b', 'c' ]

Combining Sets

Union of Two Sets

Although there is no direct method to union Sets, we can use the spread operator:

const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);
const union = new Set([...set1, ...set2]);
console.log(union); // Set(5) {1, 2, 3, 4, 5}

Intersection of Sets

The intersection of two Sets consists of the elements that are in both:

const intersection = new Set([...set1].filter((x) => set2.has(x)));
console.log(intersection); // Set(1) {3}

Difference of Sets

The difference between two Sets consists of the elements that are in one but not in the other:

const difference = new Set([...set1].filter((x) => !set2.has(x)));
console.log(difference); // Set(2) {1, 2}

Practical Examples