Remove duplicate characters from string

前端 未结 28 946
猫巷女王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
    慢半拍i (楼主)
    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
    

提交回复
热议问题