Iterator .findIndex()

QUESTION:
Let’s see if we can find the index of the first animal that starts with the letter 's' .Call .findIndex() on the animals array return the index of the first element that starts with 's' . Assign the returned value to a const variable named startsWithS .

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

/*const foundAnimal = animals.findIndex(animal => {
return animal[0] === ‘elephant’;
});
*/

const startsWithS = animals.findIndex(animal => {
return animal[0] === ‘s’ ? true : false;
});

MY QUESTION:
what is the purpose of inserting a ‘[0]’ in front of animal in …return animal[0] = ‘s’ as show above? forgive my dumb question, but I would really like to know before moving forward.

Hey @java9898360319

If I am reading your code correctly, its because the [0] signifies the first letter in the string.

Without it, the code would just check if animal was equal to 0 instead of just checking the first letter.

Here’s an example:

Your code run with [0]:
image

and without [0]:
image

You get nothing for the second one because there is no item in the array equal to just the letter “s”
Hope this Helps
Steven

Yes definitely that helped! Thank you stevencopeland!

1 Like