Skip to content
Onsite

Array.prototype.filter Polyfill

EasyP1Coding

Implement myFilter, a polyfill for Array.prototype.filter.

myFilter is called with the array as this: myFilter.call(arr, predicate, thisArg). It returns a new array with the elements for which predicate.call(thisArg, arr[i], i, arr) is truthy, in the original order.

Holes in sparse arrays are skipped. If predicate is not a function, throw a TypeError. The original array is not changed.

Example 1

Input
myFilter.call([1, 2, 3, 4], x => x % 2 === 0)
Output
[2, 4]

Example 2

Input
myFilter.call(['a', 'b', 'c'], (x, i) => i > 0)
Output
['b', 'c']

Constraints

  • 0 <= array length <= 10^5
  • Do not call the built-in Array.prototype.filter.

Hints

Run checks the 3 visible tests, Submit all 8.