I have a string with repeated letters. I want letters that are repeated more than once to show only once.
Example input: aaabbbccc
Expected output: abc
I've tried to create the code myself, but so far my function has the following problems:
- if the letter doesn't repeat, it's not shown (it should be)
- if it's repeated once, it's show only once (i.e.
aa
showsa
- correct) - if it's repeated twice, shows all (i.e.
aaa
showsaaa
- should bea
) - if it's repeated 3 times, it shows 6 (if
aaaa
it showsaaaaaa
- should bea
)
function unique_char(string) {
var unique = '';
var count = 0;
for (var i = 0; i < string.length; i++) {
for (var j = i+1; j < string.length; j++) {
if (string[i] == string[j]) {
count++;
unique += string[i];
}
}
}
return unique;
}
document.write(unique_char('aaabbbccc'));
The function must be with loop inside a loop; that's why the second for
is inside the first.