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 my function works like this:
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.
A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.
you can use . indexOf() and . lastIndexOf() to determine if an index is repeated. Meaning, if the first occurrence of the character is also the last occurrence, then you know it doesn't repeat.
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"
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'
                        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("");
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With