De-Duplicate a String
Instructions
Remove duplicate characters from a given string. Return the string with the duplicates removed.
Always keep the first instance of the character regardless of case.
Examples
Here are a few examples to illustrate how the removeDups
function works:
Example 1
Input: AaBbCcDdEeFf
Output: ABCDEF
Example 2
Input: Mississippi
Output: Misp
Example 3
Input: Hello World
Output: Helo Wrd
Solution
The example solution provided demonstrates a function called removeDups
that removes duplicate characters from a given string while preserving the first occurrence of each character, regardless of its case. The function converts the string into an array of characters, then uses a filter to iterate through the array. It keeps track of characters that have already been seen using an object, ensuring that only the first instance of each character is included in the final result. The filtered array is then joined back into a string and returned.
Remove Duplicates
removeDups = (str) => {
const userArr = str.split('')
let seen = {}
return userArr.filter((item) => {
const sameCase = item.toLowerCase()
return seen.hasOwnProperty(sameCase) ?
false
:
(seen[sameCase] = true)
}).join('')
}
An alternative solution called findDups
returns the duplicate characters from a given string. The function converts the string into an array of characters, then iterates through the array using a forEach loop. It checks if each character appears again later in the array and if it hasn't already been added to the results. If both conditions are met, the character is added to the results array. The results array is then joined back into a string and returned.
Find Duplicates
findDups = (str) => {
let userStr = str.split('')
let results = []
userStr.forEach((element, index) => {
if(userStr.indexOf(element, index + 1) > -1){
if(results.indexOf(element) === -1){
results.push(element)
}
}
})
return results.join('')
}