Search⌘ K

Remove Dupes

Explore how to create JavaScript functions that remove duplicate characters from strings while maintaining their original order. Understand two approaches: using objects and arrays for tracking uniqueness and using the ES2015 Set data structure to simplify code. Learn about the time and space complexities involved to write efficient solutions.

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'

Node.js
function removeDupes(str) {
// Your code here
}

Solution 1

Node.js
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

...