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.

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