I have been experimenting with flattening an array using an iterative approach, incorporating a stack-like structure. My goal is to flatten the array up to a certain depth for the sake of learning and exploration.
Here is what I have come up with so far:
function flattenArray(arr, depth = 1) {
let flattened = [];
let index = 0;
let currentDepth = depth;
for (let element of arr) {
flattened.push(element);
currentDepth = depth;
while(index < flattened.length) {
if (Array.isArray(flattened[index]) && currentDepth !== 0) {
flattened.splice(index, 1, ...flattened[index]);
currentDepth--;
} else {
index++;
}
}
}
return flattened;
}
However, I encountered an issue when trying to flatten a nested level such as [[3], 4, [5, [6]] because it gets stuck at the depth of '3' without reversing back.
Is there a simple adjustment that can be made to address this issue?
The original array I used was
flattenArray([[1],2,[[3], 'ddd', [4,[5]]]], 2)
, where my expected output would be [1,2,3,'ddd',4, [5]].
The same issue persists even when implementing this using a traditional stack method.