DEV Community

Cover image for Javascript Polyfill Array.flat #5
chandra penugonda
chandra penugonda

Posted on • Edited on

Javascript Polyfill Array.flat #5

This problem was asked by Meta

What is a polyfill ?

In web development, a polyfill is code that implements a feature on web browsers that do not natively support the feature

Please implement your own Array.prototype.flat()

Example

const arr = [1, [2], [3, [4]]];
flat(arr) // [1, 2, 3, [4]]
flat(arr, 1) // [1, 2, 3, [4]]
flat(arr, 2) // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Follow up: Are you able to solve it both recursively and iteratively?

Solution

Recursion implementation

if (!Array.prototype.flat) {
  Array.prototype.flat = function (depth = Infinity) {
    const result = [];
    function flatten(arr, currentdepth) {
      for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i]) && currentdepth < depth) {
          flatten(arr[i], currentdepth + 1);
        } else {
          result.push(arr[i]);
        }
      }
    }
    flatten(this, 0);
    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode

Iterative implementation

if (!Array.prototype.customFlat) {
  Array.prototype.customFlat = function (depth = Infinity) {
    const arr = [...this];
    const result = [];
    while (arr.length) {
      const current = arr.shift();
      if (Array.isArray(current) && depth > 0) {
        --depth;
        arr.unshift(...current);
      } else {
        result.push(current);
      }
    }
    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay