Skip to the solution
EasyDSAAsked in 20246 min read

Custom Array.prototype.flatmap polyfill

1.2k views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myFlatMap from scratch — mapping each element and then flattening the result by exactly ONE level, matching real native flatMap's own fixed-depth contract."

Examples:

Code
[1, 2, 3].flatMap(n => [n, n * 2]); // [1, 2, 2, 4, 3, 6]

Clarifying questions expected:

  • Is the flattening depth for flatMap genuinely fixed at exactly 1 level, with no way to configure it deeper?
  • If the callback returns a non-array value for some elements, is that value simply pushed directly, without error?
  • Is flatMap genuinely equivalent to calling map() then flat(1) separately, or is there a real, meaningful difference?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native flatMap, including a case with a doubly-nested result, confirming the ONE-level-only flattening behavior exactly.

  • js-coding
  • utility
  • algorithm

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 flatMap polyfill matches real native flatMap exactly, including that it flattens only one level deep, unlike flat(Infinity)

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 18 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

Polyfill Function.prototype.call and apply

Continue