Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Remove non-duplicate characters from string
Non-duplicate characters in a string are those that appear only once and do not repeat within the string. Sometimes in JavaScript, we need to work with strings and manipulate them based on certain conditions. One common task is to remove characters that only appear once in a string, keeping only the characters that appear more than once. In this article, we will understand how to remove non-duplicate characters from a string in JavaScript.
Understanding the Problem
Suppose we have a string like "teeth_foot". We want to remove all characters that appear only once, keeping only characters that appear multiple times. For example:
Input string:
"teeth_foot"
Expected output:
"teetoot"
Here, characters like 'h', '_', and 'f' appear only once, so they are removed. Characters 't', 'e', and 'o' appear multiple times, so they are kept.
Algorithm
To remove non-duplicate characters from a string, follow these steps:
- Convert the string into an array of characters using
split("") - Use the filter method to keep only characters that appear more than once
- Check if a character's first occurrence differs from its last occurrence using
indexOf()andlastIndexOf() - Join the filtered characters back into a string using join method
Using indexOf() and lastIndexOf()
This approach uses built-in array methods to identify duplicate characters:
const str = 'teeth_foot';
const removeNonDuplicate = str => {
const strArray = str.split("");
const duplicateArray = strArray.filter(el => {
return strArray.indexOf(el) !== strArray.lastIndexOf(el);
});
return duplicateArray.join("");
};
console.log("Original string:", str);
console.log("After removing non-duplicates:", removeNonDuplicate(str));
Original string: teeth_foot After removing non-duplicates: teetoot
Using Character Count Map
Alternative approach using a frequency map to count character occurrences:
function removeNonDuplicateWithMap(str) {
const charCount = {};
// Count frequency of each character
for (let char of str) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Filter characters that appear more than once
return str.split('').filter(char => charCount[char] > 1).join('');
}
const testStr = 'programming';
console.log("Original:", testStr);
console.log("Result:", removeNonDuplicateWithMap(testStr));
Original: programming Result: rgrmmm
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| indexOf/lastIndexOf | O(n²) | O(n) | High |
| Character Count Map | O(n) | O(n) | Medium |
Multiple Test Cases
Let's test our function with different inputs:
const removeNonDuplicate = str => {
const strArray = str.split("");
return strArray.filter(el =>
strArray.indexOf(el) !== strArray.lastIndexOf(el)
).join("");
};
const testCases = [
"hello",
"programming",
"javascript",
"aabbcc",
"abcdef"
];
testCases.forEach(test => {
console.log(`"${test}" -> "${removeNonDuplicate(test)}"`);
});
"hello" -> "ll" "programming" -> "rgrmmm" "javascript" -> "aa" "aabbcc" -> "aabbcc" "abcdef" -> ""
Conclusion
Removing non-duplicate characters from a string can be accomplished using JavaScript's built-in array methods. The indexOf/lastIndexOf approach is more readable, while the character count map method offers better performance for large strings. Both methods effectively filter out characters that appear only once in the string.
