Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 my function works like this:

  • if the letter doesn't repeat, it's not shown
  • if it's repeated once, it's show only once (i.e. aa shows a)
  • if it's repeated twice, shows all (i.e. aaa shows aaa)
  • if it's repeated 3 times, it shows 6 (if aaaa it shows aaaaaa)
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.

like image 621
Zlatko Soleniq Avatar asked Dec 13 '12 20:12

Zlatko Soleniq


People also ask

How do I check if a string has a unique character?

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.

How do you check if a character is repeated in a string Javascript?

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.


4 Answers

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"
like image 50
le_m Avatar answered Nov 15 '22 19:11

le_m


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 :-)

like image 31
Malcolm Holmes Avatar answered Nov 15 '22 20:11

Malcolm Holmes


Using lodash:

_.uniq('aaabbbccc').join(''); // gives 'abc'
like image 41
Lukasz Wiktor Avatar answered Nov 15 '22 21:11

Lukasz Wiktor


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("");
}
like image 24
Parthasarathy K Avatar answered Nov 15 '22 21:11

Parthasarathy K