Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What are Sets in JavaScript?

In this blog post, we will explore a fundamental concept in JavaScript called Sets. If you're new to programming, fear not, as we will be explaining everything in simple terms and with real-life examples. So, let's dive right in!

What is a Set?

A Set in JavaScript is a collection of unique values, which means that each value can only appear once in the Set. This is similar to a real-life set of items that you may encounter, such as a set of playing cards or a set of keys. Just like you don't want duplicates in your deck of cards or your keychain, a Set in JavaScript ensures that there are no duplicate values.

Creating a Set

Creating a Set in JavaScript is quite simple. You can use the Set constructor to create a new Set object. Here's an example:

const mySet = new Set();

This creates a new, empty Set called mySet. You can also create a Set with initial values by passing an iterable (e.g., an array) to the Set constructor:

const mySet = new Set([1, 2, 3]);

This creates a Set with the numbers 1, 2, and 3. Note that if there are duplicate values in the iterable, the Set will only store one instance of each value:

const mySet = new Set([1, 2, 2, 3, 3, 3]);
console.log(mySet); // Output: Set { 1, 2, 3 }

Adding and Removing Values

You can add values to a Set using the add method. This method takes a single argument, which is the value you want to add to the Set:

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

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

Keep in mind that adding a value that already exists in the Set will have no effect, as Sets only store unique values:

const mySet = new Set([1, 2, 3]);
mySet.add(2);
console.log(mySet); // Output: Set { 1, 2, 3 }

To remove a value from a Set, you can use the delete method, which takes the value you want to remove as an argument:

const mySet = new Set([1, 2, 3]);
mySet.delete(2);
console.log(mySet); // Output: Set { 1, 3 }

If you want to remove all values from a Set, you can use the clear method:

const mySet = new Set([1, 2, 3]);
mySet.clear();
console.log(mySet); // Output: Set {}

Checking for Values

You can check if a value is present in a Set using the has method. This method takes the value you want to check as an argument and returns a boolean value:

const mySet = new Set([1, 2, 3]);
console.log(mySet.has(2)); // Output: true
console.log(mySet.has(4)); // Output: false

Iterating over a Set

You can iterate over the values of a Set using a for...of loop:

const mySet = new Set([1, 2, 3]);

for (const value of mySet) {
  console.log(value);
}

// Output:
// 1
// 2
// 3

Alternatively, you can use the forEach method, which takes a callback function as an argument. The callback function is called for each value in the Set:

const mySet = new Set([1, 2, 3]);

mySet.forEach(value => {
  console.log(value);
});

// Output:
// 1
// 2
// 3

Set Size

You can get the number of values in a Set using the size property:

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

Converting a Set to an Array

If you need to convert a Set to an array, you can use the Array.from function or the spread operator (...):

const mySet = new Set([1, 2, 3]);

const myArray1 = Array.from(mySet);
console.log(myArray1); // Output: [ 1, 2, 3 ]

const myArray2 = [...mySet];
console.log(myArray2); // Output: [ 1, 2, 3 ]

Use Cases for Sets

Now that we've covered the basics of Sets in JavaScript, let's look at some practical use cases where Sets can be helpful.

Removing duplicates from an array

One common use case for Sets is removing duplicate values from an array. Since Sets only store unique values, you can simply convert the array to a Set and then back to an array:

const arrayWithDuplicates = [1, 2, 2, 3, 3, 3];

const uniqueArray = [...new Set(arrayWithDuplicates)];
console.log(uniqueArray); // Output: [ 1, 2, 3 ]

Checking for unique values

If you need to check if all values in an array are unique, you can compare the size of the array and the size of the corresponding Set:

const arrayWithDuplicates = [1, 2, 2, 3, 3, 3];
const uniqueArray = [1, 2, 3, 4, 5, 6];

const hasUniqueValues = array => array.length === new Set(array).size;

console.log(hasUniqueValues(arrayWithDuplicates)); // Output: false
console.log(hasUniqueValues(uniqueArray)); // Output: true

Set operations

Sets can also be useful for performing set operations, such as union, intersection, and difference:

```javascript const setA = new Set([1, 2, 3]); const setB = new Set([2, 3, 4]);

// Union: A ∪ B const union = new Set([...setA, ...setB]); console.log(union); // Output: Set { 1, 2, 3, 4 }

// Intersection: A ∩ B const intersection = new Set([...setA].filter(value => setB.has(value))); console.log(intersection); // Output: Set { 2, 3 }

// Difference: A - B const difference = new Set([...setA].filter(value => !setB.has(value))); console.log(difference); // Output: Set { 1 } ``