How to usespread Operator in Javascript

  • 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 spread operator 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"]

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