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.
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/
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");
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With