JavaScript Program to Remove Duplicates from String
[...new Set(string)].join(''), which creates a set of unique characters and joins them back into a string.Examples
How to Think About It
Algorithm
Code
function removeDuplicates(str) { return [...new Set(str)].join(''); } console.log(removeDuplicates('hello')); console.log(removeDuplicates('javascript')); console.log(removeDuplicates('aaaaaa'));
Dry Run
Let's trace 'hello' through the code
Input string
'hello'
Convert to Set
Set {'h', 'e', 'l', 'o'}
Spread Set into array
['h', 'e', 'l', 'o']
Join array into string
'helo'
| Iteration | Character | Set Content |
|---|---|---|
| 1 | h | {'h'} |
| 2 | e | {'h', 'e'} |
| 3 | l | {'h', 'e', 'l'} |
| 4 | l | {'h', 'e', 'l'} |
| 5 | o | {'h', 'e', 'l', 'o'} |
Why This Works
Step 1: Using Set to Remove Duplicates
A Set in JavaScript stores only unique values, so converting the string to a set removes repeated characters automatically.
Step 2: Spreading Set into Array
The spread operator ... converts the set back into an array so we can join the characters.
Step 3: Joining Characters
Using .join('') combines the array of unique characters back into a single string without duplicates.
Alternative Approaches
function removeDuplicates(str) { return str.split('').filter((char, index, arr) => arr.indexOf(char) === index).join(''); } console.log(removeDuplicates('hello'));
function removeDuplicates(str) { let seen = {}; let result = ''; for (let char of str) { if (!seen[char]) { seen[char] = true; result += char; } } return result; } console.log(removeDuplicates('hello'));
Complexity: O(n) time, O(n) space
Time Complexity
The code loops through each character once to create the set, so it runs in linear time relative to the string length.
Space Complexity
A set stores unique characters, so extra space grows with the number of unique characters, up to the string length.
Which Approach is Fastest?
Using Set is generally fastest and simplest; filter/indexOf is slower due to repeated searches; manual loop is clear but more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set and spread | O(n) | O(n) | Fastest and simplest for most cases |
| filter and indexOf | O(n²) | O(n) | Easy to understand but slower for long strings |
| Loop with object | O(n) | O(n) | Clear manual control, good for learning |
new Set() to quickly remove duplicates from any iterable like strings or arrays.