let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
2 , and
1 (the first index at which each element exists).
Apparently so… but how? Why?
In the array itself it should be (using pseudocode)…
‘apples’ = index 0
‘pears’ = index 1
‘oranges’ = index 2
‘peaches’ = index 3
‘pears’ = index 4
Is it starting over after “oranges” and then considering “peaches” to be index 0 then “pears” index 1?
**Your browser information:**
User Agent is:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0
Challenge: Check For The Presence of an Element With indexOf()
Link to the challenge:
PS: I see that is says
"the first index at which each element exists" but this seems ambiguous and not a clear explanation of why / how the method is operating that it would give that result.
If I’m interpreting your question correctly, you’re asking why “dates” returns -1?
When you use Array.indexof(), if the element isn’t contained in the array it always returns -1.
Am I interpreting correctly?
No, I’m asking why
fruits.indexOf('pears'); returns 1 when the actual array index of “pears” is 4.
Just realized you have “pears” put twice. Array.indexof() only works if you have a single element with that matching value. I’m not sure why it’s changing that value after you run it again, I can’t replicate that with your code. If you show us the rest we might be able to help more
The code is being copy / pasted from the challenge. My question is regarding the content of the challenge information. In the challenge the information given in the left column says that
fruits.indexOf('pears'); returns 1 and when that code is run it is indeed returning 1. But the array index of that element is 4 not 1. So I’m wanting to learn what that method is doing. I thought it was supposed to return the array index that the element is at (which would be 4). So what is really going on here?
^ That’s what the challenge says (its a screenshot)
It’s always going to return the first index that it appears in. It won’t ever return 4 because it won’t get that far. It interprets it from left to right. Try running it in the console, 4 never shows up
There is also a “pears” at index 1. That’s the one that it’s returning because it’s the first time it appears.
OH shit!! I’m a complete idiot. How did I not see that?
If I delete this post will I also delete my shame along with it?
Have you been coding for like 6 hours?
Regardless of how long you’ve been at it, things like that are basically guaranteed. I remember one time I spent hours debugging something because I put function parameters in the wrong order. It happens!
The brain is also kinda funny like that sometimes. Your brain misses little details all the time. It’s like the the longer you stare, the more you miss. Did you notice the second “the” in the last sentence? If not, you know why you missed the second “pears”