I have a challenge where I need to create a function that takes an array. The array is filled with strings that are all the same except for one, which is spelled backwards. I need to identify the string and return its index position.
The code I tried is the following
const petList = ['god','dog', 'dog', 'dog']
function findWrongWayWord(pets) {
const petOne = pets[0];
if (pets.length<3) {
return 0;
}
for (let i = 1; i < pets.length; i++) {
if (pets[i] !== petOne) {
return pets.indexOf(pets[i]);
}
}
}
findWrongWayWord(petList)
And sort of works, but only that when the word that’s backwards is at the start of the array, it does not return the right index.
2
Answers
if all the items in an array are same except the one, then all you need is a non repeated distinct unique value in array.
We search for the index for each value from the start and from the last value. If those are the same index, only one exists.
Edit: The answer by Syed is a lot more elegant, I’ll leave this as an alternative solution to solve these kinds of challanges
The reason it only works for the first one, is because you only check it against the first one (
const petOne = pets[0]
). You could loop through everything, but there is a simpler logic:However long your array is, when you find the match (even though we dont know that yet), you only need two other values. You need 3 values to determine the odd one out.
The rules to make this work:
Please note: untested code