Showing Unique Characters In A String Only Once
I have a string with repeated letters. I want letters that are repeated more than once to show only once. For instance I have a string aaabbbccc i want the result to be abc. so far
Solution 1:
Fill a Set
with the characters and concatenate its unique entries:
function makeUnique(str) {
return String.prototype.concat(...new Set(str))
}
console.log(makeUnique('abc')); // "abc"
console.log(makeUnique('abcabc')); // "abc"
Solution 2:
Convert it to an array first, then use the answer here, and rejoin, like so:
var nonUnique = "ababdefegg";
var unique = nonUnique.split('').filter(function(item, i, ar){ return ar.indexOf(item) === i; }).join('');
All in one line :-)
Solution 3:
Too late may be but still my version of answer to this post:
function extractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
return Object.keys(temp).join("");
}
Solution 4:
You can use a regular expression with a custom replacement function:
function unique_char(string) {
return string.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeat
return ""; // its not shown
if (sequence.length == 2) // if its repeated once
return char; // its show only once (if aa shows a)
if (sequence.length == 3) // if its repeated twice
return sequence; // shows all(if aaa shows aaa)
if (sequence.length == 4) // if its repeated 3 times
return Array(7).join(char); // it shows 6( if aaaa shows aaaaaa)
// else ???
return sequence;
});
}
Solution 5:
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Post a Comment for "Showing Unique Characters In A String Only Once"