Thursday, September 4, 2025
HomeLanguagesJavascriptHow to Convert Array to Set in JavaScript?

How to Convert Array to Set in JavaScript?

The task is to convert a JavaScript Array to a Set with the help of JavaScript. We are going to discuss a few approaches: 

Approach:

  • 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 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"]
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS