Implement the filter Method on a Prototype

Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line
for (let i = 0; i < newArray.length; i += 1) {
  if (newArray.push(this.Array[i]));
}
  // Only change code above this line
  return newArray;
};

I have no clue what to do for this problem. I’m so lost…please help :sob:

What is the length of newArray?

What is Array?


  • You need to check the length on the this array, not the empty array you created.

  • You need to call the callback and pass it each of the this array elements and the loop index. Only if the callback function returns a truthy value do you then push to the new array.

  • You should push the current element of the this array.

There is no length of newArray because it is an empty array[ ]. This worked. Thanks!

Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line
for (let i = 0; i < this.length; i += 1) {
  if (Boolean(callback(this[i], i, this)) === true) {
    newArray.push(this[i]); 
  }
}
  // Only change code above this line
  return newArray;
};

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