Showing unique characters in a string only once

后端 未结 13 2257
-上瘾入骨i
-上瘾入骨i 2020-12-31 20:38

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.

相关标签:
13条回答
  • 2020-12-31 20:45

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

    0 讨论(0)
  • 2020-12-31 20:45

    Using lodash:

    _.uniq('aaabbbccc').join(''); // gives 'abc'
    
    0 讨论(0)
  • 2020-12-31 20:45

    Here is the simplest function to do that

      function remove(text) 
        {
          var unique= "";
          for(var i = 0; i < text.length; i++)
          {
            if(unique.indexOf(text.charAt(i)) < 0) 
            {
              unique += text.charAt(i);
            }
          }
          return unique;
        }
    
    0 讨论(0)
  • 2020-12-31 20:46

    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"

    0 讨论(0)
  • 2020-12-31 20:46
    const countUnique = (s1, s2) => new Set(s1 + s2).size
    

    a shorter way based on @le_m answer

    0 讨论(0)
  • 2020-12-31 20:47

    Your problem is that you are adding to unique every time you find the character in string. Really you should probably do something like this (since you specified the answer must be a nested for loop):

    function unique_char(string){
    
        var str_length=string.length;
        var unique='';
    
        for(var i=0; i<str_length; i++){
    
            var foundIt = false;
            for(var j=0; j<unique.length; j++){
    
                if(string[i]==unique[j]){
    
                    foundIt = true;
                    break;
                }
    
            }
    
            if(!foundIt){
                unique+=string[i];
            }
    
        }
    
       return unique;
    }
    
    document.write( unique_char('aaabbbccc'))
    

    In this we only add the character found in string to unique if it isn't already there. This is really not an efficient way to do this at all ... but based on your requirements it should work.

    I can't run this since I don't have anything handy to run JavaScript in ... but the theory in this method should work.

    0 讨论(0)
提交回复
热议问题