Missing Letters - spelling out entire alphabet seems clunky

So none of the solutions seem to include comparing str to the entire alphabet list. How can this be cleaned up?

function fearNotLetter(str) {

let alpha = ["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"];
let strasarr = str.split("");

// console.log(strasarr);

//get the letter at which strasarr starts
let letterposition = alpha.indexOf((strasarr[0]));

for (var i = 0; i < strasarr.length; i++){
  if(strasarr[i] !== alpha[letterposition]){
    return alpha[letterposition];
  }else{
    letterposition++;
  }
}
}


fearNotLetter("abce");

First of all, the solutions do cover all of the letters, they just do it with math.

But going with your idea, I think it can be simplified a bit with:

function fearNotLetter(str) {
  const alpha = new Array(26).fill(1).map((_, i) => String.fromCharCode(97 + i));
  
  const start = alpha.indexOf((str[0]));

  for (let i = 1; i < str.length; i++) {
    if (str[i] !== alpha[start + i]) {
      return alpha[start + i];
    }
  }
  return undefined;
}

You have an unnecessary counting variable (letterposition) in there, imho. You only need one counting variable to index.

If the way we construct the alpha array is too arcane, this:

const alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');

would work as well.

1 Like