Hi,
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
animal[0]
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??
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.
'hippo'[0]
exactly!
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.
But thatâs not whatâs in the code. This is not in the code anywhere:
animals[0]
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