FrontendInterviews.dev

Loading problem…

73. Array.prototype.filter (Polyfill)

Easy•
Acceptance: 95.65%
•
🔓3/3 Pro unlocks today

Implement Array.prototype.myFilter — a polyfill that behaves like native Array.prototype.filter.

Filter creates a new array containing all elements for which the callback returns a truthy value.

Requirements

1) Core behavior

  • Return a new array.
  • Invoke callbackFn for each existing element (skip holes).
  • Callback signature: (value, index, array).
  • Preserve original order of kept elements.
  • Support optional thisArg for callbackFn.

2) Edge cases

  • Throw TypeError if callbackFn is not a function.
  • Capture the array length at start (pushes beyond original length are not visited).
  • Sparse arrays: skip holes (missing indices) entirely.

Constraints

  • Must not use Array.prototype.filter internally.
  • callbackFn must be a function; otherwise throw TypeError.
  • Callback receives (value, index, array).
  • Skip holes in sparse arrays (do not call callback for missing indices).
  • Preserve element order.
  • Support optional thisArg binding via callbackFn.call(thisArg, ...).
  • Capture length at start; items pushed beyond original length are not visited.