Intermediate Algorithm Scripting: Missing letters - using arrays

Hello Campers! :alien:

I just finished the algorithm challenge for missing letters and here’s the link: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

I’m supposed to return a missing letter from the input string range.

I think it would’ve been more efficient if I used the CharCodeAt() and fromCharCode() functions as suggested in the hint, but my initial approach without the help of the hint was to use what I already felt more comfortable with… the array!

So here’s my solution (and it passed the test):

function fearNotLetter(str) {
  let alphabets = "abcdefghijklmnopqrstuvwxyz";
  // Put all alphabets in an array.
  let alphaArr = [].concat(alphabets.split(''));
  // Get all input string into an array as well.
  let inputStr = [].concat(str.split(''));
  
  // Get the range of alphabets to check for missing letter
  let firstIndex = alphaArr.indexOf(inputStr[0]);
  let lastIndex = alphaArr.indexOf(inputStr[inputStr.length-1]);
  
  // If the range of inputStr is shorter than the range of the alphabets list, filter the array to find the missing letter.
  if (inputStr.length !== lastIndex - firstIndex + 1) {
    return alphaArr.slice(firstIndex,lastIndex+1)
                   .filter(missingAlpha => inputStr.indexOf(missingAlpha) == -1)[0];
  } else {
    return undefined;
  }
}

It’s nice that the code works, but can anyone let me know of a better (more efficient) way to filter through the array to return the missing character? I think using the suggested CharCodeAt() wouldn’t make sense since I’m using arrays, but I feel a little guilty for not using the char-related functions for this specific challenge.

Thanks!

Well, you don’t need arrays for your code to work, except slice to return an array to filter. I think explicitly returning undefined is fine but you don’t need to, as that is the default return value of any function.

function fearNotLetter(str) {
  // Alphabet
  const alphabet = 'abcdefghijklmnopqrstuvwxyz';

  // Get the range of alphabets to check for missing letter
  const firstIndex = alphabet.indexOf(str[0]);
  const lastIndex = alphabet.indexOf(str[str.length - 1]);

  // If the range of str is shorter than the range of the alphabets list, filter the array to find the missing letter.
  if (str.length !== lastIndex - firstIndex + 1) {
    return Array.from(alphabet.slice(firstIndex, lastIndex + 1)).filter(
      missingAlpha => str.indexOf(missingAlpha) == -1
    )[0];
  }
}

Not sure I would really call it much of an improvement but I just wanted to point it out.

Hey @lasjorg, thanks for your thoughts.
The array definitely wasn’t necessary after looking over yours :smile: