Introduction

I'm delighted to welcome you to our JavaScript Sets lesson! Remember, sets are like arrays or objects, except they can only hold unique elements. They're especially useful when you need to guarantee that elements in a collection appear only once.

In this lesson, you'll consolidate your knowledge of creating and operating on sets. You will learn about the advantages of using sets and how they enhance performance. Ready, Set, Go!

Creating and Manipulating Sets

Let's begin by creating a set in JavaScript. It can be done using the Set() constructor.

// Creating a set and printing it
let mySet = new Set([1, 2, 3, 4, 5, 5, 5]); // Duplicates will be omitted
console.log(mySet); // Output: Set(5) { 1, 2, 3, 4, 5 }

JavaScript provides methods to manipulate sets, such as add(), has(), delete(), and clear().

// Adding an element
mySet.add(6); // mySet is now Set { 1, 2, 3, 4, 5, 6 }

console.log(mySet.has(1)); // Output: true, as `mySet` includes an element 1

// Removing an element
mySet.delete(1); // mySet becomes Set { 2, 3, 4, 5, 6 }

console.log(mySet.has(1)); // Output: false, as `mySet` doesn't include 1 anymore

// Clearing the set
mySet.clear(); // mySet becomes an empty set
console.log(mySet); // Output: Set(0) {}
  • add(): Adds a specified element to the set.
  • has(): Checks if the specified element exists in the set.
  • delete(): Removes a specified element from the set.
  • clear(): Removes all elements from the set.
Set Operations

JavaScript does not directly provide built-in methods for operations such as union, intersection, and difference for sets, but they can be implemented using standard JavaScript.

let set1 = new Set([1, 2, 3, 4]); // First set
let set2 = new Set([3, 4, 5, 6]); // Second set

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

// Set intersection
let intersection = new Set([...set1].filter(x => set2.has(x)));
console.log(intersection); // Output: Set(2) { 3, 4 }

// Set difference
let difference = new Set([...set1].filter(x => !set2.has(x)));
console.log(difference); // Output: Set(2) { 1, 2 }
  • union: Combines elements from both sets, excluding any duplicates. In this case, the result is a set containing {1, 2, 3, 4, 5, 6}.
  • intersection: Returns a set with only the elements that are common to both sets. For these sets, the intersection is {3, 4}.
  • difference: Returns a set containing elements that are in the first set but not in the second set. Here, the result is {1, 2} for set1.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal