I am attempting to solve this challenge:
This function receives an array of fruits (orchard), where all fruits are spelled correctly except for one. The function is tasked with identifying the index position of the misspelled fruit. For instance, in the given example, the function should return 0.
['graep', 'grape', 'grape', 'grape']
This is what I have so far:
function findWrongWayFruit(orchard) {
if (orchard.length < 3) {
return 0;
}
const firstFruit = orchard[0];
for (let i = 1; i < orchard.length; i++) {
if (firstFruit !== orchard[i]) {
return i;
}
}
return 0;
}
console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));
However, when I try to run this code, the only test case that failed was this: Should return the correct index when the wrong-way fruit is at start’ (AssertionError: expected 1 to equal +0)
4
Answers
Your logic is incorrect as you assumed firstFruit to be correct and the consequent fruits are wrong if they spell differently. Instead you can use 2 counts, one for correct spelling and the other for wrong spelling. The count==1 will be the one incorrectly spelled.
When the inner
if
condition is true, buti
is 1, there are still two options: the index to return could be either 0 or 1. To know which one, you should make one more comparison that involves another value in the array (like at index 2). If that one is different fromfirstFruit
, then you knowfirstFruit
is the deviating value, and you should return 0.A quick solution is to change your inner
return
statement to this:You could take an array for the indices, depending on the value which are stored in the references object and assign a false index if a reference is already found.
Finally return if two values are in the indices array and if a false index is set.