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

  1. Throw TypeError for null/undefined this or a non-function callback.
  2. Object(this) and length >>> 0, read once.
  3. Only visit existing indexes (i in O); unlike map, the result is dense (no holes) because you push matches.
  4. 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.
  5. Truthiness, not strict true: filter(Boolean) must work.
  6. 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 undefined for 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`);
5
6 const O = Object(this);
7 const len = O.length >>> 0;
8 const result = [];
9
10 for (let i = 0; i < len; i++) {
11 if (!(i in O)) continue; // skip holes
12 const value = O[i]; // read before calling the predicate
13 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});
21
22const 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 result
26
27// thisArg
28const range = { min: 2, max: 4 };
29console.log(numbers.myFilter(function (n) { return n >= this.min && n <= this.max; }, range)); // [2, 3, 4]
30
31// Always a new array
32const all = numbers.myFilter(() => true);
33console.log(all !== numbers, all.length); // true 6
34
35// Array-likes
36console.log(Array.prototype.myFilter.call("hello", (c) => c !== "l")); // ["h", "e", "o"]
37
38delete 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.

Open in study app