Array.prototype.filter Polyfill

ArraysPolyfill

Implement Array.prototype.myFilter that behaves identically to the native filter.

Function Signature:

Array.prototype.myFilter = function (callback, thisArg) { }

Requirements:

  • Throw TypeError if callback is not a function
  • Return a new array containing only the elements for which callback returns truthy
  • Push the original element, not the boolean result
  • Pass (element, index, array) to each callback invocation
  • Respect the optional thisArg

Examples

Example 1
Input
[1, 2, 3, 4, 5].myFilter(x => x % 2 === 0)
Output
[2, 4]
Explanation
Only elements where the predicate is true are kept.
Example 2
Input
['apple', 'banana', 'cherry'].myFilter(s => s.length > 5)
Output
['banana', 'cherry']
Explanation
Strings longer than 5 characters pass the predicate.

Constraints

  • Do not use the native Array.prototype.filter internally
  • Use push, not index assignment — the output array is denser than the input

Notes

  • The most common mistake: `result.push(callback(...))` — you want `result.push(this[i])`

Hints

Read the full write-up for Array.prototype.filter Polyfill
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it