Functional Programming - Implement the filter Method on a Prototype

I used every solution and then this is the solution that was posted but I have an error:
For this example [1,1,2,5,2] this method didn’t work. But why?
The answer should be 1,2,5 but my answer is 1,1,5.

Your code so far

var s = [1,1,2,5,2];
Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line
  for (const i of this) {
    if (callback(i)) newArray.push(i);
  }
  // Only change code above this line
  return newArray;
};

var new_s = s.myFilter(function(item){
  return item % 2 === 1;
});

console.log(new_s); //print [1,1,2]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

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

Link to the challenge:

You aren’t using all three arguments of the callback.

The challenge was changed recently but no one changed the solutions in the Guide.

for (let i of this) {
if (callback(this[i],i,this)) newArray.push(i);
}

I tried but I think I didn’t understand the point of the question right. :smiling_face_with_tear: If “this” is our array, this[i] should be element and i should be index. Am I wrong?

Thanks for your answer :pray:

i would be the element in a for…of loop, not the index.

You can look at Solution 3 to see a way to get the index in a for…of loop.

const numbers = [23, 65, 98, 5];

for (const [index, element] of numbers.entries()) {
  console.log({ index });
  console.log({ element });
}