How to usethe Set Constructor in Javascript

  • Create a Set from the Array
  • Convert Set back to an Array
  • Output the result

Example: In this example we are using the set constructor.

Javascript
const array = [1, 2, 2, 3, 4, 4, 5];

// Convert array to Set
const setFromArr = new Set(array);

// Convert Set back to array (if needed)
const newArray = Array.from(setFromArr);

// Output
console.log(setFromArr); // Output: Set { 1, 2, 3, 4, 5 }
console.log(newArray);   // Output: [1, 2, 3, 4, 5]

Output
Set(5) { 1, 2, 3, 4, 5 }
[ 1, 2, 3, 4, 5 ]

How to Convert Array to Set in JavaScript?

The goal is to transform a JavaScript Array into a Set using JavaScript’s built-in features. This process involves taking all the elements from the array and putting them into a Set, which is a data structure that only contains unique values. By doing this conversion, we can efficiently manage and operate on the array’s elements without worrying about duplicates.

Below are the approaches to Converting Array to a Set in JavaScript:

Table of Content

  • Approach 1: Using spread Operator
  • Approach 2: Using the Set Constructor
  • Approach 3: Using the forEach Loop

Similar Reads

Approach 1: Using spread Operator

Take the JavaScript array into a variable.Use the new keyword to create a new set and pass the JavaScript array as its first and only argument.This will automatically create the set of the provided array....

Approach 2: Using the Set Constructor

Create a Set from the ArrayConvert Set back to an ArrayOutput the result...

Approach 3: Using the forEach Loop

In this approach, we iterate over each element of the array using the forEach() loop and add each element to the Set. This method allows for explicit control over the transformation process and is particularly useful for performing additional operations on array elements before adding them to the Set....

Contact Us