Method 1: Using JavaScript's `Set` Object (The Modern Way)
The Set object is a collection of unique values. This makes it perfect for our use case. We can convert the string into an array of characters, pass it to a Set, and then convert it back to a string.
Code Example:
function removeDuplicatesUsingSet(str) {
// 1. Convert string to an array of characters
const chars = str.split('');
// 2. Create a Set from the array (automatically handles uniqueness)
const uniqueChars = new Set(chars);
// 3. Convert the Set back to an array
const uniqueCharsArray = Array.from(uniqueChars);
// 4. Join the array characters back into a string
return uniqueCharsArray.join('');
}
// Or more concisely:
function removeDuplicatesConciseSet(str) {
return Array.from(new Set(str.split(''))).join('');
}
console.log(removeDuplicatesUsingSet("hello world")); // Output: "helo wrd"
console.log(removeDuplicatesConciseSet("programming")); // Output: "progamin"
console.log(removeDuplicatesConciseSet("aabbccddeeff")); // Output: "abcdef"
Explanation:
str.split(''): Splits the string into an array of individual characters. E.g., "hello" becomes['h', 'e', 'l', 'l', 'o'].new Set(...): Creates a new Set. When you pass an iterable (like an array) to the Set constructor, it automatically adds only the unique elements. Sonew Set(['h', 'e', 'l', 'l', 'o'])becomes a Set containing{'h', 'e', 'l', 'o'}.Array.from(...): Converts the Set back into an array..join(''): Joins the characters in the array back into a single string.
Method 2: Using `filter()` and `indexOf()`
This method involves converting the string to an array, and then using the filter() method with indexOf() to keep only the first occurrence of each character.
Code Example:
function removeDuplicatesUsingFilter(str) {
return str.split('').filter((char, index, arr) => {
// Keep the character only if its first occurrence is at the current index
return arr.indexOf(char) === index;
}).join('');
}
console.log(removeDuplicatesUsingFilter("banana")); // Output: "ban"
console.log(removeDuplicatesUsingFilter("javascript")); // Output: "javscript"
Explanation:
str.split(''): Again, converts the string to an array of characters..filter((char, index, arr) => { ... }): Iterates over each character (char) at itsindexwithin the originalarr.arr.indexOf(char) === index: This is the core logic.indexOf()returns the index of the first occurrence of a character. If the character's currentindexmatches theindexOf()result, it means this is the first time we've encountered this character, so we keep it. If it's a duplicate, itsindexOf()will point to an earlier index, and the condition will befalse, thus filtering it out..join(''): Joins the filtered characters back into a string.
Method 3: Manual Iteration with a Lookup Object/Set
For those who prefer a more fundamental approach or want to understand the logic without built-in higher-order functions, you can iterate through the string and build a new one, keeping track of seen characters.
Code Example:
function removeDuplicatesManual(str) {
let uniqueString = '';
const seenChars = {}; // Could also use a new Set() here for seen characters
for (let i = 0; i < str.length; i++) {
const char = str[i];
if (!seenChars[char]) { // If character hasn't been seen before
uniqueString += char; // Add to our unique string
seenChars[char] = true; // Mark character as seen
}
}
return uniqueString;
}
console.log(removeDuplicatesManual("programming is fun")); // Output: "progamin sf"
console.log(removeDuplicatesManual("mississippi")); // Output: "misippi"
Explanation:
uniqueString: An empty string that will build up our result.seenChars: An empty object (orSet) used as a hash map/set to quickly check if a character has already been added.- The
forloop iterates through each character of the input string. if (!seenChars[char]): Checks if the current charactercharis not a property in ourseenCharsobject. If it's not, it means we haven't encountered it yet.- If new, the character is appended to
uniqueString, and thenseenChars[char] = truemarks it as seen so it won't be added again.
Which Method to Choose?
For most modern JavaScript applications, the Set method (Method 1) is generally the most recommended. It's:
- Concise: Very little code needed.
- Readable: The intent (getting unique values) is clear due to the use of
Set. - Efficient:
Setoperations are highly optimized.
The filter() with indexOf() method (Method 2) is also elegant but can be less performant for very long strings because indexOf() potentially iterates through a portion of the array for each character.
The manual iteration (Method 3) is great for understanding fundamental algorithm design and might be preferred in environments where Set isn't available (though rare now) or for specific performance micro-optimizations depending on character set and string length.