Open In App

How to Convert Array to Set in JavaScript?

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to convert a JavaScript Array to a Set with the help of JavaScript.

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

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.

Example 1: In this example, the array is converted into a set using the same approach defined above. 

Javascript




let A = [1, 1, 2, 2, 2, 2, 5, 5];
 
function GFG_Fun() {
    let set = new Set(A);
    console.log(JSON.stringify([...set]));
}
 
GFG_Fun();


Output

[1,2,5]

Example 2: In this example, the array is converted into a set using a bit approach than above. 

Javascript




let Arr = ["A", "A", "Computer Science", "portal",
    "for", "for", "Geeks", "Geeks"];
 
function GFG_Fun() {
    let set = new Set(Arr);
     
    console.log(JSON.stringify([...set.keys()]));
}
 
GFG_Fun();


Output

["A","Computer Science","portal","for","Geeks"]

Approach 2: Using the Set Constructor

  • 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 ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads