JavaScriptEasy
Create a polyfill for filter()
A filter polyfill walks the array, calls the predicate with (element, index, array) and the optional thisArg, and pushes the element into a new array whenever the predicate returns a truthy value, skipping holes and never mutating the original.
Spec details
- Throw
TypeErrorfornull/undefinedthisor a non-function callback. Object(this)andlength >>> 0, read once.- Only visit existing indexes (
i in O); unlikemap, the result is dense (no holes) because you push matches. - Read the value before calling the predicate and push that value, so changes the callback makes to the array do not affect what you push.
- Truthiness, not strict
true:filter(Boolean)must work. - Return a new array.
Common interview mistakes
- Using an arrow function for the method, which breaks
this. - Returning the original array when everything matches (must be a new array).
- Pushing
undefinedfor holes.
Complexity
O(n) time, O(k) space for k matches.
Code example
js
1Object.defineProperty(Array.prototype, "myFilter", {2 value: function myFilter(predicate, thisArg) {3 if (this == null) throw new TypeError("Array.prototype.myFilter called on null or undefined");4 if (typeof predicate !== "function") throw new TypeError(`${predicate} is not a function`);56 const O = Object(this);7 const len = O.length >>> 0;8 const result = [];910 for (let i = 0; i < len; i++) {11 if (!(i in O)) continue; // skip holes12 const value = O[i]; // read before calling the predicate13 if (predicate.call(thisArg, value, i, O)) result.push(value);14 }15 return result;16 },17 writable: true,18 configurable: true,19 enumerable: false,20});2122const numbers = [1, 2, 3, 4, 5, 6];23console.log(numbers.myFilter((n) => n % 2 === 0)); // [2, 4, 6]24console.log([0, "a", null, 1, "", NaN].myFilter(Boolean)); // ["a", 1]25console.log([1, , 3].myFilter(() => true)); // [1, 3] - dense result2627// thisArg28const range = { min: 2, max: 4 };29console.log(numbers.myFilter(function (n) { return n >= this.min && n <= this.max; }, range)); // [2, 3, 4]3031// Always a new array32const all = numbers.myFilter(() => true);33console.log(all !== numbers, all.length); // true 63435// Array-likes36console.log(Array.prototype.myFilter.call("hello", (c) => c !== "l")); // ["h", "e", "o"]3738delete Array.prototype.myFilter;
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.