Home ยป JavaScript Sets: A Complete Tutorial with Examples

JavaScript Sets: A Complete Tutorial with Examples

In JavaScript, a Set is a collection of unique values of any type, whether primitive or object references.

Sets are useful when you want to store a list of items where duplicates are not allowed.

Introduced in ES6 (ECMAScript 2015), Sets provide several built-in methods to add, remove, and manipulate their elements efficiently.

1. Creating a Set

A Set can be created using the new Set() constructor. You can pass an iterable (like an array) to initialize the Set with values.

Example 1: Creating an Empty Set

let mySet = new Set();
console.log(mySet); // Output: Set(0) {}

Example 2: Creating a Set from an Array

let numbers = [1, 2, 3, 4, 5, 3, 2, 1];
let uniqueNumbers = new Set(numbers);

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

Explanation

The new Set() constructor creates a Set object.

When initializing a Set with an array ([1, 2, 3, 4, 5, 3, 2, 1]), it automatically removes duplicates, resulting in { 1, 2, 3, 4, 5 }.

2. Adding Elements to a Set

You can add elements to a Set using the .add() method. Note that adding duplicate values has no effect on the Set.

Example 3: Using .add() Method

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate value
mySet.add('Hello');

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

Explanation

mySet.add(2) is called twice, but the Set only keeps one instance of 2.
A Set only stores unique values.

3. Removing Elements from a Set

The .delete() method is used to remove an element from the Set.

Example 4: Using .delete() Method

let mySet = new Set([1, 2, 3]);
mySet.delete(2);

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

Explanation

mySet.delete(2) removes the element 2 from the Set.
If the element is not found, delete() returns false.

4. Checking for Elements in a Set

You can use the .has() method to check if a particular element exists in the Set.

Example 5: Using .has() Method

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

console.log(mySet.has(2)); // Output: true
console.log(mySet.has(5)); // Output: false

Explanation

mySet.has(2) returns true because 2 is present in the Set.
mySet.has(5) returns false because 5 is not in the Set.

5. Finding the Size of a Set

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

Example 6: Using .size Property

let mySet = new Set(['apple', 'banana', 'cherry']);
console.log(mySet.size); // Output: 3

Explanation

.size gives the number of unique elements in the Set (3 in this case).

6. Clearing All Elements from a Set

The .clear() method removes all elements from the Set.

Example 7: Using .clear() Method

let mySet = new Set([1, 2, 3]);
mySet.clear();

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

Explanation

mySet.clear() removes all elements from the Set, resulting in an empty Set.

7. Iterating Over a Set

You can use loops to iterate over the elements of a Set. The most common way is using for…of.

Example 8: Using for…of Loop

let mySet = new Set([1, 2, 3, 4, 5]);

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

Output

1
2
3
4
5

Explanation

The for…of loop iterates over each element in the Set in the order they were added.

Example 9: Using forEach() Method

let mySet = new Set(['apple', 'banana', 'cherry']);

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

Output

apple
banana
cherry

Explanation

The forEach() method executes a provided function for each element in the Set.

8. Converting a Set to an Array

To convert a Set back to an array, you can use the spread operator (…) or the Array.from() method.

Example 10: Using Spread Operator

let mySet = new Set([1, 2, 3, 4, 5]);
let myArray = [...mySet];

console.log(myArray); // Output: [1, 2, 3, 4, 5]

Example 11: Using Array.from() Method

let mySet = new Set(['a', 'b', 'c']);
let myArray = Array.from(mySet);

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

Explanation

Both the spread operator ([…]) and Array.from() method convert the Set into an array.

9. Working with Sets: Basic Set Operations

Example 12: Union of Two Sets

let setA = new Set([1, 2, 3]);
let setB = new Set([3, 4, 5]);

let unionSet = new Set([...setA, ...setB]);
console.log(unionSet); // Output: Set(5) { 1, 2, 3, 4, 5 }

Explanation

The spread operator (…) merges the elements of setA and setB into a new Set (unionSet), automatically removing duplicates.

Example 13: Intersection of Two Sets

let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);

let intersectionSet = new Set([...setA].filter(value => setB.has(value)));
console.log(intersectionSet); // Output: Set(2) { 2, 3 }

Explanation

The .filter() method creates a new Set containing only the elements present in both setA and setB.

Example 14: Difference of Two Sets

let setA = new Set([1, 2, 3]);
let setB = new Set([2, 3, 4]);

let differenceSet = new Set([...setA].filter(value => !setB.has(value)));
console.log(differenceSet); // Output: Set(1) { 1 }

Explanation

The .filter() method creates a new Set containing elements from setA that are not in setB.

Summary

JavaScript Sets provide an efficient way to handle collections of unique values.

They are particularly useful when you need to ensure that a list contains no duplicates. Here's a quick recap of the key Set operations:

 

Common Methods and Properties

Method/Property Description
new Set(iterable) Creates a new Set, optionally from an iterable (e.g., array).
.add(value) Adds a new element to the Set.
.delete(value) Removes a specific element from the Set.
.has(value) Checks if an element exists in the Set.
.size Returns the number of elements in the Set.
.clear() Removes all elements from the Set.
.forEach(callback) Executes a callback for each element in the Set.

Key Points

  • Unique Values: A Set automatically removes duplicate values.
  • Iterating: You can use for...of or .forEach() to iterate through the elements.
  • Set Operations: Use sets for operations like union, intersection, and difference.

By mastering Sets in JavaScript, you can handle unique collections of data more efficiently in your programs.

You may also like