Remove duplicate characters from string

前端 未结 28 727
猫巷女王i
猫巷女王i 2020-12-01 13:09

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

相关标签:
28条回答
  • 2020-12-01 13:51

    DEMO

    function find_unique_characters( string ){
        unique=[];
        while(string.length>0){
            var char = string.charAt(0);
            var re = new RegExp(char,"g");
            if (string.match(re).length===1) unique.push(char);
            string=string.replace(re,"");
        }        
        return unique.join("");
    }
    console.log(find_unique_characters('baraban')); // rn
    console.log(find_unique_characters('anaconda')); //cod
    ​
    
    0 讨论(0)
  • 2020-12-01 13:54

    Try this code, it works :)

    var str="anaconda";
    Array.prototype.map.call(str, 
     (obj,i)=>{
      if(str.indexOf(obj,i+1)==-1 && str.lastIndexOf(obj,i-1)==-1){
       return obj;
      }
     }
    ).join("");
    //output: "cod"
    
    0 讨论(0)
  • 2020-12-01 13:57
      //One simple way to remove redundecy of Char in String
           var char = "aaavsvvssff"; //Input string
           var rst=char.charAt(0);
           for(var i=1;i<char.length;i++){              
               var isExist = rst.search(char.charAt(i));
                isExist >=0 ?0:(rst +=  char.charAt(i) ); 
           }
           console.log(JSON.stringify(rst)); //output string : avsf
    
    0 讨论(0)
  • 2020-12-01 13:57
        function removeDuplicates(str) {
           var result = "";
           var freq = {};
           for(i=0;i<str.length;i++){
            let char = str[i];
            if(freq[char]) {
              freq[char]++;     
            } else {
               freq[char] =1
               result +=char;
           }
        }
      return result;
    }
    
    0 讨论(0)
提交回复
热议问题