-1

The task I am undertaking is as follows:

The function should be called removeDuplicates and should return an object literal containing a 'uniques' property, which should be the sorted input string but without any duplicates or special characters. The returned object should also have a 'duplicates' property which should represent the total number of duplicate characters dropped. So: removeDuplicates('th#elex_ash?') should return: {uniques: 'aehlstx', duplicates: 2}

Here is my code:

function removeDuplicates(str) {
    var stg = str.split("");
    var nstr = [];
    var allowed = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var count = 0;
    for(var i = 0; i<stg.length;i++){
        if(nstr.indexOf(stg[i])== -1){
            if(allowed.indexOf(stg[i]) > -1){
                nstr.push(str[i])
            }
            else{
                count +=1;
            }
        }
    }
    return{uniques: nstr.sort().join(""),duplicates: count}

}

But the result returns {uniques: 'aehlstx', duplicates: 3} instead.

danoseun
  • 69
  • 2
  • 9

2 Answers2

0

Because you are counting the not allowed characters :)

Lorenzo Cinque
  • 954
  • 1
  • 14
  • 22
0

You are checking first if you've seen the character before, and THEN checking it was an allowed character and counting the number of times you see a non-allowed character. You need to check if the character is allowed, and then see if you've seen it before.

Matt_S
  • 315
  • 1
  • 7