Last Updated : 12 Jul, 2025
The Set constructor is used to convert the array into set in JavaScript. It is useful to clean the array and remove duplicate elements. Converting Array to Set means transforming the array elements into a Set object.
Using Set ConstructorThe Set constructor in JavaScript directly converts an array into a Set. This process automatically filters out duplicate elements, creating a collection of unique values. It's a simple and efficient way to manage distinct data in an array.
Syntax
let newSet = new Set( a )JavaScript
// Create array using array literal
let a = [1, 1, 2, 2, 2, 2, 5, 5];
// Convert to set using the set constructor
let s = new Set(a);
// Display the output
console.log(s);
Set(3) { 1, 2, 5 }
This is the simple and fastest method to Convert Array to Set in JavaScript, because the constructor handles the entire array at once. This method is suitable when we have large array size.
If you want to handle some additional checks/conditions while converting Array to set, above method may not be best choice. For such cases, you can choose below given method.
Using set.add() MethodWe can also convert the array into set by adding the elements one by one. To do this we will iterate the array using forEach loop and push the elements into Set, using set.add() method.
Syntax
set.add( value );
This add function checks if the value already exist in the set or not. If the value is not found, it pushes the value to set otherwise skips adding the element.
JavaScript
// Create array using array literal
let a = [1, 1, 2, 2, 2, 2, 5, 5];
// Initialize enpty set using the set constructor
let s = new Set();
// Iterate over the array and add the elements to set
a.forEach( e => s.add(e) );
// Display the output
console.log(s);
Set(3) { 1, 2, 5 }
When you want to manipulate elements dynamically (any check or modification) then this method can be used, else using constructor is recommended.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4