What does animal[0] do?

In the code why animal[0] ?
in the previous codes they only mentioned animal or some other parameters but they did not use [0] . why [0] is used here?

the instructions:

Let’s see if we can find the index of the first animal that starts with the letter 's'

to get the first character of a string, we need to access by index. Which [0] does

this is not clear. in an array, [0] will return the first element and not the first character of each element.

the requirement to return the index of the element that starts with “s” should be a string manipulation function (like substr (size_t pos = 0, size_t len = npos) ).

so home come animal[0] is the solution??

1 Like

It isn’t being used on an array.

Given a string, look at its first character, compare to s, determine whether the string meets the criteria

Repeat for each string.

what do you mean not an array??

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

that’s not an array declaration?

That’s an array. And that isn’t the value that is being looked at. It’s one of the strings in it that is being looked at.


so animals[0] is NOT looking inside each element of an array but on the first element only.
to look at each element and find the first character of each, there should be a string operator like substr(). plus looping.

correct me if i’m wrong in my assumptions. really confused.

1 Like

But that’s not what’s in the code. This is not in the code anywhere:

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

that’s the answer from the tutorial. see, how can animal[0] look at each element’s first character??

It doesn’t.
You’re mixing up a single animal with an array of animals. That function does not look at the array at all. It does not mention the array. It doesn’t do any operations involving the array.

it is comparing the array animal so it’s doing operation involving the array.

let me quote the explanation of .findIndex()

Calling .findIndex() on an array will return the index of the first element that evaluates to true in the callback function.

how does it move within the array’s element then? to look at each element’s first character?

The callback function doesn’t move within the array, it is completely unaware of the array.
It looks at one string.
Array.findIndex does the rest.

Array.findIndex calls the callback function on each element of the array until the callback returns true or the end of the array is reached.

I’m confused. So callbackFunctionParameter[0] === 's'runs through the first letter of each string in an array?

yes, given findIndex will pass each element in the array to the parameter of your callback function

1 Like