Showing unique characters in a string only once

character, javascript, string, unique

Solution

Fill a `Set` with the characters and concatenate its unique entries:

function unique(str) {
  return String.prototype.concat.call(...new Set(str));
}

console.log(unique('abc'));    // "abc"
console.log(unique('abcabc')); // "abc"

Problem

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` shows `a` - correct) - if it's repeated twice, shows all (i.e. `aaa` shows `aaa` - should be `a`) - if it's repeated 3 times, it shows 6 (if `aaaa` it shows `aaaaaa` - should be `a`) ``` 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.

Original source

Related problems