I am currently working on developing a custom polyfill for the Array.flat() method. However, I have encountered some challenges when trying to call the function recursively within itself to flatten nested arrays further. It seems that when I write code without using prototypes, the flattening works correctly. But once I attempt to create a prototype function, I cannot achieve the desired flattened array. I suspect that the issue lies with the 'this' keyword. Please review my code below.
Below is the code snippet:
let arrayFlat = [1, 2, 3, [4, 5, 6, [7, 8, [9]], 10, [11, 12]], [13, [14, 15]]];
const flatArray = (array) => {
let output = [];
const flatten = (array) => {
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
flatten(array[i]);
} else {
output.push(array[i]);
}
}
return output;
};
return flatten(array);
};
Array.prototype.myFlat = function () {
let output = [];
for (let i = 0; i < this.length; i++) {
if (Array.isArray(this[i])) {
console.log(this[i]);
this[i].myFlat();
} else {
output.push(this[i]);
}
}
return output;
};