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:
functionmakeUnique(str) {
returnString.prototype.concat(...newSet(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:
functionextractUniqCharacters(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
temp[str.charAt(oindex)] = 0; //Assign any value
}
returnObject.keys(temp).join("");
}
Solution 4:
You can use a regular expression with a custom replacement function:
function unique_char(string) {
returnstring.replace(/(.)\1*/g, function(sequence, char) {
if (sequence.length == 1) // if the letter doesn't repeatreturn""; // its not shownif (sequence.length == 2) // if its repeated oncereturnchar; // its show only once (if aa shows a)if (sequence.length == 3) // if its repeated twicereturn sequence; // shows all(if aaa shows aaa)if (sequence.length == 4) // if its repeated 3 timesreturn 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"