FAQ: Iterators - The .findIndex() Method

Hello

Could someone help me? My console.log(start with) shows only ‘3’ but there is another word ‘salamander’ in 6, the printing should be 3 and 6. Why it is printing only 3?

thanks

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex (animal=>
{return animal === 'elephant';
}
);

const startsWithS = animals.findIndex(animal =>
{ return animal[0]=== 's'? true:false;
}
)
console.log(startsWithS);
console.log(foundAnimal); 

Hello
Sorry it is me again , now i have tried with another way by using .charAt but it is printing -1 instead of 3 and 6 . Could you please explain me what is happened ?

thanks

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex (animal=>

{return animal === ‘elephant’;
}
);

const startsWithS = animals.findIndex(

animal => {

return animal.charAt[0]===‘s’ ? true:false;
}
)

console.log(startsWithS);

console.log(foundAnimal);

This is a method, not an iterable.

string.charAt(0)

Thank you @mtf .

Now I changed as a method but it is still coming out 3.
There is another word ‘salamander’ in 6, the printing should be 3 and 6. Why it is printing only 3?

const animals = [‘hippo’, ‘tiger’, ‘lion’, ‘seal’, ‘cheetah’, ‘monkey’, ‘salamander’, ‘elephant’];

const foundAnimal = animals.findIndex (animal=>

{return animal === ‘elephant’;
}
);

const startsWithS = animals.findIndex(

animal => {

return animal.charAt(0)===‘s’ ? true:false;

}
)
console.log(startsWithS);

console.log(foundAnimal);

1 Like

If you look at the findIndex method documentation:

Array.prototype.findIndex() - JavaScript | MDN

you will see it says:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function .

1 Like

thank you @stetim94 , so the answer is right as it will return only for the first element.