Remove duplicate characters from string

前端 未结 28 834
猫巷女王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条回答
  •  -上瘾入骨i
    2020-12-01 13:37

    1. If you want your function to just return you a unique set of characters in your argument, this piece of code might come in handy. Here, you can also check for non-unique values which are being recorded in 'nonUnique' titled array:

      function remDups(str){
          if(!str.length)
              return '';
          var obj = {};
          var unique = [];
          var notUnique = [];
          for(var i = 0; i < str.length; i++){
              obj[str[i]] = (obj[str[i]] || 0) + 1;
          }
          Object.keys(obj).filter(function(el,ind){
              if(obj[el] === 1){
                  unique+=el;
              }
              else if(obj[el] > 1){
                  notUnique+=el;
              }
          });
      return unique;
      }
      console.log(remDups('anaconda')); //prints 'cod'
      
    2. If you want to return the set of characters with their just one-time occurrences in the passed string, following piece of code might come in handy:

      function remDups(str){
          if(!str.length)
              return '';
          var s = str.split('');
          var obj = {};
          for(var i = 0; i < s.length; i++){
              obj[s[i]] = (obj[s[i]] || 0) + 1;
          }
          return Object.keys(obj).join('');
      }
      console.log(remDups('anaconda')); //prints 'ancod'
      

提交回复
热议问题