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
TypeErrorifcallbackis 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
Editorial: Array.prototype.filter Polyfill
Implementing Array.prototype.filter from scratch
filter returns a new array containing only the elements for which the callback returns a truthy value. Same callback signature and thisArg as map.
What the interviewer checks
The single most common mistake: pushing the boolean result of the callback instead of the original element. A surprising number of candidates write result.push(callback(...)).
Implementation
Array.prototype.myFilter = function (callback, thisArg) { if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } const result = []; for (let i = 0; i < this.length; i++) { if (i in this && callback.call(thisArg, this[i], i, this)) { result.push(this[i]); } } return result; };
Key details
- Push
this[i], not the callback's return value — you want the original element, nottrue. pushnot index assignment — the output array is denser than the input (filtered elements are contiguous), so index assignment would leave gaps.i in this— same sparse-array hole check asmap.- The callback still receives all three arguments:
(element, index, array).
Edge cases to mention
- An empty array returns
[]with no errors. thisArgworks the same way as inmap.- Holes in sparse arrays are skipped, so
[1,,3].myFilter(x => x > 0)should produce[1, 3].
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it