Functional Programming - Implement the filter Method on a Prototype

Tell us what’s happening:
Describe your issue in detail here.
This code does work but I do not fully understand it. I understand it until I get to the last challenge which states.

[1, 1, 2, 5, 2].myFilter((element, index, array) => array.indexOf(element) === index) should return [1, 2, 5].

I do not understand why this[i], i, this is the correct parameters to pass in order to make it run correctly.
Your code so far

Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line
for (let i = 0; i < this.length; i++) {
    if(callback(this[i], i, this))
      newArray.push(this[i])
}
  // Only change code above this line
  return newArray;
};
console.log([1, 1, 2, 5, 2].myFilter((element, index, array) => array.indexOf(element) === index))

Your browser information:

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

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

Link to the challenge:

When you call your function, this is what is to the left of the dot.

[1, 1, 2, 5, 2].myFilter((el........
               ↑
            the dot

So this, when that example is called, is an array, [1, 1, 2, 5, 2].

So substitute that array for this in your logic, what’s the result?


Just for future reference, this is almost always whatever is to the left of the dot when a function is called. That “whatever” is always an object.

It is useful to override that behaviour occasionally. So JavaScript does provide a few ways to do that, to tell a function to use a different object when it’s called (these are the methods apply, call, and bind, which are attached to the Function object just like you’re attaching methods to the Array object).

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