Remove Dupes

In this lesson, we'll discuss how to remove duplicates from a string. We'll cover two different solutions and see how ES2015 constructs can greatly simplify our code.

We'll cover the following...

Remove Dupes

Instructions

Write a function that takes in a string and returns a new string. The new string should be the same as the original with every duplicate character removed.

Input: String

Output: String

Examples

'abcd' -> 'abcd'
'aabbccdd' -> 'abcd'
'abcddbca' -> 'abcd'
'abababcdcdcd' -> 'abcd'

Press + to interact
function removeDupes(str) {
// Your code here
}

Solution 1

Press + to interact
function removeDupes(str) {
const characters = {};
const uniqueCharacters = [];
for(let i = 0; i < str.length; i++) {
const thisChar = str[i];
if(!characters[thisChar]) {
characters[thisChar] = true;
uniqueCharacters.push(thisChar);
}
}
return uniqueCharacters.join('');
}

How it Works

...