call(back)

Implement Array.prototype.filter

Write Array.prototype.myFilter(cb, thisArg) so it matches the built-in filter. The grader disables the native map, filter, reduce and concat while your code runs.

Rules

  • Call cb.call(thisArg, value, index, array) for each element and keep the elements whose result is truthy. A callback that isn't a function throws TypeError.
  • Skip holes: never call back for them, and never copy them into the result.
  • Return a new array. Define the method with function, not an arrow, so this is the array.
[1, 2, 3, 4].myFilter((v) => v % 2 === 0)   // [2, 4]
[1, , 2].myFilter(() => true)               // [1, 2]

Tests write a hole as "<hole>"; the grader turns it into a real empty slot and back. Callbacks are named in each test's input and supplied by the grader.

Hints

Hint 1

i in this tells a hole from a stored undefined — skip the holes entirely.

Hint 2

Unlike map, filter's output is shorter than its input, so push the kept elements instead of writing by index.

Asked at