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.
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 :-)
Using lodash:
_.uniq('aaabbbccc').join(''); // gives 'abc'
Here is the simplest function to do that
function remove(text)
{
var unique= "";
for(var i = 0; i < text.length; i++)
{
if(unique.indexOf(text.charAt(i)) < 0)
{
unique += text.charAt(i);
}
}
return unique;
}
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"
const countUnique = (s1, s2) => new Set(s1 + s2).size
a shorter way based on @le_m answer
Your problem is that you are adding to unique
every time you find the character in string
. Really you should probably do something like this (since you specified the answer must be a nested for loop):
function unique_char(string){
var str_length=string.length;
var unique='';
for(var i=0; i<str_length; i++){
var foundIt = false;
for(var j=0; j<unique.length; j++){
if(string[i]==unique[j]){
foundIt = true;
break;
}
}
if(!foundIt){
unique+=string[i];
}
}
return unique;
}
document.write( unique_char('aaabbbccc'))
In this we only add the character found in string
to unique
if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.
I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.