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]
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)