Skip to the solution
EasyDSA6 min read

Polyfill Array.prototype.filter from scratch

630 views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myFilter from scratch — matching real native filter's own documented contract, including its real hole-skipping behavior on a sparse array."

Examples:

Code
[1,2,3,4,5,6].myFilter(n => n % 2 === 0); // [2, 4, 6]

Clarifying questions expected:

  • Does the callback receive the index and whole array, matching real native's own documented signature?
  • Should a real hole in a sparse array be skipped entirely — never invoking the callback, and never appearing in the result?
  • Is the result a genuinely NEW array, or should it mutate the original?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native filter, including on a real sparse array, confirming identical output.

  • polyfill
  • array
  • filter

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the filter polyfill matches the real native method exactly, including on a real sparse array where holes never invoke the callback or appear in the result

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 35 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement intersection of arrays (with duplicates & order)

Continue