0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Array to Set Easily

You can convert an array to a set in JavaScript by passing the array to the Set constructor like this: new Set(array).
📋

Examples

Input[1, 2, 3]
OutputSet {1, 2, 3}
Input[1, 2, 2, 3, 3, 3]
OutputSet {1, 2, 3}
Input[]
OutputSet {}
🧠

How to Think About It

To convert an array to a set, think of a set as a collection that only keeps unique values. You take the array and give it to the set constructor, which automatically removes duplicates and stores only unique items.
📐

Algorithm

1
Get the input array.
2
Create a new set by passing the array to the Set constructor.
3
Return the new set containing unique elements.
💻

Code

javascript
const array = [1, 2, 2, 3, 4, 4];
const set = new Set(array);
console.log(set);
Output
Set { 1, 2, 3, 4 }
🔍

Dry Run

Let's trace the array [1, 2, 2, 3, 4, 4] through the code

1

Input array

[1, 2, 2, 3, 4, 4]

2

Create set from array

new Set([1, 2, 2, 3, 4, 4])

3

Resulting set

Set {1, 2, 3, 4}

StepValue
1[1, 2, 2, 3, 4, 4]
2Set {1, 2, 3, 4}
💡

Why This Works

Step 1: Set constructor removes duplicates

When you pass an array to new Set(), it automatically keeps only unique values, removing any duplicates.

Step 2: Set stores unique elements

A Set is a special object that stores unique items, so converting an array to a set filters out repeated values.

🔄

Alternative Approaches

Using Array.from() with Set
javascript
const array = [1, 2, 2, 3];
const uniqueArray = Array.from(new Set(array));
console.log(uniqueArray);
This converts the array to a set and back to an array to get unique elements as an array.
Using spread operator with Set
javascript
const array = [1, 2, 2, 3];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
This also converts the array to a set and back to an array using spread syntax for simplicity.

Complexity: O(n) time, O(n) space

Time Complexity

Creating a set from an array takes O(n) time because it processes each element once to check for uniqueness.

Space Complexity

The set stores unique elements, so in the worst case it uses O(n) space if all elements are unique.

Which Approach is Fastest?

Using new Set(array) is the fastest and simplest way to convert an array to a set. Converting back to an array adds extra steps.

ApproachTimeSpaceBest For
new Set(array)O(n)O(n)Getting unique elements as a set
Array.from(new Set(array))O(n)O(n)Getting unique elements as an array
[...new Set(array)]O(n)O(n)Getting unique elements as an array with concise syntax
💡
Use new Set(array) to quickly remove duplicates from an array.
⚠️
Trying to convert a set back to an array without using Array.from() or spread syntax.