Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the characters in a string which are not duplicated

I have to make a function in JavaScript that removes all duplicated letters in a string. So far I've been able to do this: If I have the word "anaconda" it shows me as a result "anaconda" when it should show "cod". Here is my code:

function find_unique_characters( string ){
    var unique='';
    for(var i=0; i<string.length; i++){
        if(unique.indexOf(string[i])==-1){
            unique += string[i];
        }
    }
    return unique;
}
console.log(find_unique_characters('baraban'));
like image 355
Zlatko Soleniq Avatar asked Dec 12 '12 13:12

Zlatko Soleniq


People also ask

How do you find non repeated characters in a string?

Using the indexOf() and lastIndexOf() method, we can find the first non-repeating character in a string in Java. The method indexOf() returns the position of the first occurrence of a given character in a string whereas method lastIndexOf() returns the position of the last occurrence of a given character in a string.

How do I check if a string has repeated characters?

If we want to know whether a given string has repeated characters, the simplest way is to use the existing method of finding first occurrence from the end of the string, e.g. lastIndexOf in java. In Python, the equivalence would be rfind method of string type that will look for the last occurrence of the substring.


1 Answers

Using Set:

removeDuplicates = str => [...new Set(str)].join('');

Thanks to David comment below.

like image 196
Paras Avatar answered Oct 15 '22 13:10

Paras