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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object
- JavaScript – Shuffle an array in a random orderTo shuffle an array in random order in JavaScript, you can use the sort() function with Math.random() or use the map() & sort() function. Let’s… Read more: JavaScript – Shuffle an array in a random order