DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 3: Polyfill for Array.flat()

Today, we'll create a polyfill for the Array.flat() method.
The Array.flat() method flattens nested arrays to a specified depth. Our goal is to create a function called myFlat that will implement this behavior.

// Test cases
const array = [1, [2], [3, [3]]];

console.log(array.myFlat()); // Output: [1, 2, 3, [3]]
console.log(array.myFlat(1)); // Output: [1, 2, 3, [3]]
console.log(array.myFlat(3)); // Output: [1, 2, 3, 3]
console.log(array.myFlat(Infinity)); // Output: [1, 2, 3, 3]
Enter fullscreen mode Exit fullscreen mode

Plan

To solve this problem, we'll follow these steps:

  • Implement the myFlat function to recursively flatten the array.
  • The myFlat function will take an optional depth parameter that specifies the depth to which the array should be flattened.
  • Check if the Array.prototype.myFlat property exists.
  • If it doesn't exist, create a new property called myFlat on Array.prototype and assign it a function.

Check the comment below to see answer.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
// Check if Array.prototype.myFlat exists
if (!Array.prototype.myFlat) {
  Array.prototype.myFlat = function (depth = 1) {
    // Function to flatten the array recursively
    const flatten = (arr, currentDepth) => {
      // Base case: depth reached or array is not an array
      if (currentDepth === 0 || !Array.isArray(arr)) {
        return arr;
      }

      // Recursive case: flatten each element in the array
      return arr.reduce((result, element) => {
        if (Array.isArray(element)) {
          return result.concat(flatten(element, currentDepth - 1));
        }
        return result.concat(element);
      }, []);
    };

    return flatten(this, depth);
  };
}

// Test cases
const array = [1, [2], [3, [3]]];

console.log(array.myFlat()); // Output: [1, 2, 3, [3]]
console.log(array.myFlat(1)); // Output: [1, 2, 3, [3]]
console.log(array.myFlat(3)); // Output: [1, 2, 3, 3]
console.log(array.myFlat(Infinity)); // Output: [1, 2, 3, 3]
Enter fullscreen mode Exit fullscreen mode

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