Write a function that takes an array of consecutive (increasing) letters as input and that returns the missing letter in the array. It will be always exactly one letter be missing. The array will always contain letters in only one case. Example:
["a","b","c","d","f"] -> "e" ["O","Q","R","S"] -> "P"
Why don't my functions work?
function findMissingLetter(array)
{
let alphabetArr = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
let alphabetSlice = alphabetArr.slice(alphabetArr.indexOf(array[0]), alphabetArr.indexOf(array[array.length - 1]) + 1);
let missingLetter = alphabetSlice.forEach((e, i) => {
if (e !== array[i]) {
return e;
}
});
return missingLetter;
}
function findMissingLetter(array)
{
let alphabetArr = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
let alphabetSlice = alphabetArr.slice(alphabetArr.indexOf(array[0]), alphabetArr.indexOf(array[array.length - 1]) + 1);
let missingLetter = alphabetSlice.map((e, i) => {
if (e !== array[i]) {
return e;
}
})[0];
return missingLetter;
}
For searching for one element in an array use for loop, like this:
for(let i = 0; i < array.length; i++) {
if(array[i] !== alphabetSlice[i])
return alphabetSlice[i];
}
In this approach you will search for first difference between two arrays. And the difference will be your missing letter :)
map function takes data and replaces it with "re-arranged" data. This:
alphabetSlice.map((e, i) => {
if (e !== array[i]) {
return e;
}
}); // for your example will create array
will create [undefined, undefined, undefined, undefined, 'e', 'f'], so the first element is undefined.
undefined?Because you have return statement in if. So when the expression in if is false, you won't return any value, so the value is undefined.
More about map you can read on mdn.
Actually just replace forEach with find and change what you're returning, and it will do what's needed.
function findMissingLetter(array)
{
let alphabetArr = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
let alphabetSlice = alphabetArr.slice(alphabetArr.indexOf(array[0]), alphabetArr.indexOf(array[array.length - 1]) + 1);
let missingLetter = alphabetSlice.find((e, i) => e !== array[i]);
return missingLetter;
}
console.log(findMissingLetter(["a","b","c","d","f"]))
console.log(findMissingLetter(["O","Q","R","S"]))
Array.prototype.forEach() executes a provided function once for each array element.
Array.prototype.find() returns the value of the first element in the provided array that satisfies the provided testing function.
There is no way to return from a forEach loop before it iterates through each element.
And forEach always returns undefined.
You can find the letter with const missingLetter = alphabetSlice.find((e, i) => e !== array[i]);