JavaScript – Find Missing Letter in an Array

In this post, we will see how to find the missing letter from an array of alphabets in JavaScript. Missing letter from an array can be found using the below methods:

Methods to find missing letter from array

  • Using a loop
  • Using Array.find() method
  • Using Array.findIndex() method

Using a loop

function findMissingLetter(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    if (arr[i].charCodeAt() + 1 !== arr[i + 1].charCodeAt()) {
      return String.fromCharCode(arr[i].charCodeAt() + 1);
    }
  }
  return undefined;
}
console.log(findMissingLetter(['a','c','d']));  // b

In this example, we loop through the array and check for the missing letter by comparing the character codes of adjacent letters.

Using Array.find() method

const findMissingLetter = arr => (cur =>
    String.fromCharCode(arr.find(ch => ch.charCodeAt() != cur++)?.charCodeAt() - 1)
)(arr[0].charCodeAt());

console.log(findMissingLetter(['a','c','d'])); // b

Instead of using a loop, we used the Array.find() built-in method.

Using Array.findIndex() method

const findMissingLetter = (array) => {
  const index = array
    .slice(1) // create an array with 1st letter removed
    .findIndex((c, i) => c.charCodeAt() - array[i].charCodeAt() > 1);
        
  return index > -1 ? 
    String.fromCharCode(array[index].charCodeAt() + 1) : null;
  };

console.log(findMissingLetter(['a', 'b', 'c', 'e'])); // d

In the above example, we compared the current letter and the same index in the original array using the findIndex() method until found the missing letter.

If the index was found return the next letter after the last letter in a sequence otherwise return null.

Similar Reads