Remove duplicate characters from string

前端 未结 28 726
猫巷女王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:31

    Method 1 : one Simple way with just includes JS- function

    var data = 'sssssffffdffffdffffddfffffff';
    
        var ary = [];
        var item = '';
        for (const index in data) {
          if (!ary.includes(data[index])) {
            ary[index] = data[index];
            item += data[index];
          }
        }
        console.log(item);
    

    Method 2 : Yes we can make this possible without using JavaScript function :

    var name = 'sssssffffdffffdffffddfffffff';
    
    let i = 0;
    let newarry = [];
    
    for (let singlestr of name) {
        newarry[i] = singlestr;
        i++;
    }
    
    
    // now we have new Array and length of string
    length = i;
    
    function getLocation(recArray, item, arrayLength) {
    
        firstLaction = -1;
        for (let i = 0; i < arrayLength; i++) {
    
            if (recArray[i] === item) {
                firstLaction = i;
                break;
            }
    
        }
    
        return firstLaction;
    
    }
    
    
    let finalString = '';
    for (let b = 0; b < length; b++) {
       
        const result = getLocation(newarry, newarry[b], length);
        if (result === b) {
            finalString += newarry[b];
        }
    
    }
    console.log(finalString); // sdf
    
    0 讨论(0)
  • 2020-12-01 13:32

    Here's what I used - haven't tested it for spaces or special characters, but should work fine for pure strings:

    function uniquereduce(instring){ 
        outstring = ''
        instringarray = instring.split('')
        used = {}
        for (var i = 0; i < instringarray.length; i++) {
            if(!used[instringarray[i]]){
                used[instringarray[i]] = true
                outstring += instringarray[i]
            }
        }
        return outstring
    }
    
    0 讨论(0)
  • 2020-12-01 13:33

    This should work using Regex ;
    NOTE: Actually, i dont know how this regex works ,but i knew its 'shorthand' , so,i would have Explain to you better about meaning of this /(.+)(?=.*?\1)/g;. this regex only return to me the duplicated character in an array ,so i looped through it to got the length of the repeated characters .but this does not work for a special characters like "#" "_" "-", but its give you expected result ; including those special characters if any

    function removeDuplicates(str){
        var REPEATED_CHARS_REGEX = /(.+)(?=.*?\1)/g;
        var  res = str.match(REPEATED_CHARS_REGEX);
        var word = res.slice(0,1);
        var raw = res.slice(1);
        var together = new String (word+raw);
        var fer = together.toString();
        var length = fer.length;
        // my sorted duplicate;
          var result = '';
          for(var i = 0; i < str.length; i++) {
            if(result.indexOf(str[i]) < 0) {
              result += str[i];
            }
          }
    
          return {uniques: result,duplicates: length};
        } removeDuplicates('anaconda')
    

    The regular expression /([a-zA-Z])\1+$/ is looking for:

    ([a-zA-Z]]) - A letter which it captures in the first group; then \1+ - immediately following it one or more copies of that letter; then $ - the end of the string. Changing it to /([a-zA-Z]).*?\1/ instead searches for:

    ([a-zA-Z]) - A letter which it captures in the first group; then .*? - zero or more characters (the ? denotes as few as possible); until \1 - it finds a repeat of the first matched character.

    0 讨论(0)
  • 2020-12-01 13:34

    Using Set() and destructuring twice is shorter:

    const str = 'aaaaaaaabbbbbbbbbbbbbcdeeeeefggggg';
    
    const unique = [...new Set([...str])].join('');
    
    console.log(unique);

    0 讨论(0)
  • 2020-12-01 13:34
    console.log(("anaconda").split('').sort().join('').replace(/(.)\1+/g, ""));
    

    By this, you can do it in one line.

    output: 'cdo'

    0 讨论(0)
  • 2020-12-01 13:36
       function removeDuplicates(string){
          return string.split('').filter((item, pos, self)=> self.indexOf(item) == pos).join('');
       }
    

    the filter will remove all characters has seen before using the index of item and position of the current element

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