Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a string for missing letters of the alphabet in javascript

Tags:

javascript

I'm working on a bit of code that will search through a string and return any letters of the alphabet that are missing. This is what I have:

function findWhatsMissing(s){
    var a = "abcdefghijklmnopqrstuvwxyz";
    //remove special characters
    s.replace(/[^a-zA-Z]/g, "");
    s = s.toLowerCase();
    //array to hold search results
    var hits = [];

    //loop through each letter in string
    for (var i = 0; i < a.length; i++) {
        var j = 0;
        //if no matches are found, push to array
        if (a[i] !== s[j]) {
                hits.push(a[i]);
        }
        else {
            j++;
        }
    }
    //log array to console
    console.log(hits);
}

But using the test case: findWhatsMissing("d a b c");

Results in all the letters before d being added to the missing array.

Any help would be greatly appreciated.

like image 539
J. Johnson Avatar asked Feb 24 '16 21:02

J. Johnson


3 Answers

Inside your loop, you can use indexOf() to see if the letter exists in your input. Something like this would work:

for (var i = 0; i < a.length; i++) {
    if(s.indexOf(a[i]) == -1) { hits.push(a[i]); }
}

Hope that helps! You can see it working in this JS Fiddle: https://jsfiddle.net/573jatx1/1/

like image 124
Adam Konieska Avatar answered Nov 19 '22 14:11

Adam Konieska


As Adam Konieska says. Something like this will work:

   function findWhatsMissing(s) {
        var a = "abcdefghijklmnopqrstuvwxyz";
        s = s.toLowerCase();
        var hits = [];
        for (var i = 0; i < a.length; i++) {
            if(s.indexOf(a[i]) == -1) { hits.push(a[i]); }
        }

       console.log(hits);
    }

    findWhatsMissing("d a b c");
like image 45
Sam Saint-Pettersen Avatar answered Nov 19 '22 14:11

Sam Saint-Pettersen


Can use Array.prototype.filter() and within each loop check string using indexOf()

function findWhatsMissing(s){
    var a = "abcdefghijklmnopqrstuvwxyz";
    //remove special characters
    s = s.replace(/[^a-zA-Z]/g, "");
    s = s.toLowerCase();
    return a.split('').filter(function(letter){
      return s.indexOf(letter) === -1;
    });
}

alert( findWhatsMissing('d f v'))
like image 2
charlietfl Avatar answered Nov 19 '22 15:11

charlietfl