Implement the Filter Method on a Prototype

The condition is that the element should be equal to its index in the array.
The array is [1, 1, 2, 5, 2].

[1, 1, 2, 5, 2].indexOf(1) === 0 which is false
[1, 1, 2, 5, 2].indexOf(1) === 1 which is true
[1, 1, 2, 5, 2].indexOf(2) === 2 which is true
[1, 1, 2, 5, 2].indexOf(5) === 3 which is false
[1, 1, 2, 5, 2].indexOf(2) === 4 which is false

So, the new array should contain [1, 2] but the tests expect the new array to contain [1, 2, 5]

I think the test case has an error, either it should be 3 instead of 5, or , the new array should contain [1, 2]

Challenge: Functional Programming - Implement the filter Method on a Prototype

Link to the challenge:

Why would that be false?

Sorry I meant to say that [1,1,2,5,2].indexOf(5) === 3 which is not equal to 5, as the test requires that the index of element in array should be equal to the element. In this case 3 being the index of 5 in the array whereas 5 is the element

That’s not what the test says though. The first index of 5 is 3

Oh, now I got it. The test case was checking if the first index of the element in the array should be equal to the index of the element. I had thought that the index of element in the array should be equal to the element. Thank you for your help.

I’m unable to understand How it is identifying the first index??,
can you please elaborate more clearly with another example or something…

My doubt lies here…
when it is testing the same element 2nd time to another index,
How will another index get to know that the element is already assigned to a index before??

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Take an array:- arr [1, 1, 1, 2, 2]
In this array, arr.indexOf(1) is always 0 and arr.indexOf(2) is always 3, no matter how many times they are repeated in the array.

In the above problem:

indexOf(1) = 0, index = 0      (returns **true**)
indexOf(1) = 0, index = 1      (returns false)
indexof(2) = 2, index = 2       (returns **true**)
indexof(5) = 3, index = 3       (returns **true**)
indexof(2) = 2, index = 4       (returns false)

So, it will return [1, 2, 5]

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.