Day 3: Polyfill for Array.flat()

1 min read ❤️ 0 · 💬 1
#day3 #100daysofcode #javascript

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.


Originally published on DEV Community . Read the discussion and share your thoughts there.

© 2026

LinkedIn 𝕏 GitHub