Find unique Characters in a String
Hey ππ»,
Today Iβll be discussing how can we find out the unique characters in a string using different approaches and languages. Lets start π
Using Set
There are a few ways we can use to find the unique characters in a string. The simplest way is by using the Set. The Set object lets you store unique values of any type, whether primitive values or object references.
Letβs name the function returning unique string as removeDupes, that accepts the original string as input.
function removeDupes(str) {
// Split the string into array of characters using the split() method.
let arr = str.split()// Create a new set from the array of characters
let demoSet = new Set(arr)// The formation of set will remove all the duplicate items. Now we can use the Array
// for storing the values.
let arrayNew = Array.from(demoSet)// Empty string to store final answer
var uniqueStr = ββ// Use the forEach loop to iterate over the array
arrayNew.forEach(element => {
uniqueStr += element
})return uniqueStr
}
Using Objects / Hashmaps
Other viable option to find the unique elements in a string can be using the objects / hashmaps. We can simply store the character and the number of its occurrences. Later we can simply print the occurrence of a character once.
This approach is quite useful when there are certain conditions mentioned for example to only print the last occurrence of the character etc.
// Empty Object to store chars and their count
// e.g: { a : 2, b : 1 }
let listOfChars = {};function removeDupes(str) {
// Split the array
let arr = str.split(ββ);// Populate the values in the Object
for (var i = 0; i < arr.length; i++) {
if (isNaN(listOfChars[arr[i]])) {
listOfChars[arr[i]] = 1;
} else {
listOfChars[arr[i]] += 1;
}
}// Unique String / Final Answer
var uniqueStr = ββ;// Using the forin loop to iterate over Object
for (key in listOfChars) {
if (listOfChars[key] >= 1) {
uniqueStr += key;
listOfChars[key] = 0;
}
}return uniqueStr;
}
Using the filter method
In the filter method we can check the position of a character and and them filter them out at their first index using the indexOf method.
function removeDupes(str) {
return str.split(ββ)
.filter(function(item, pos, self) {
// Find the index of a character and filter it out.
return self.indexOf(item) == pos;
})
.join(ββ);
}
I hope this blog post was useful for you.
I also write technical blog on Hashnode. Follow me for more such content. https://mayankkhanna.hashnode.dev/