I want to flatten an array with javascript but without recurssion and without prebuilt function.
This is the code but it dose not flatten the whole array and i want to know what is wrong with my code
input : [1, [2], [3,8, [[4]],9],[5,6]]
output : [1, 2, 3, 8, 5, 6]
Code :
flat = function(array) {
const output = []
for (let i = 0; i < array.length; i++) {
if (typeof array[i] == 'number') {
output.push(array[i])
} else {
let arr = array[i]
let n = 0
while (n < arr.length) {
if (typeof arr[n] == 'number') {
output.push(arr[n])
n++
} else {
arr = arr[n]
n--
console.log(arr, n);
}
}
}
}
return output
}
It's possible to do, but it involves managing a stack yourself, manually:
const input = [1, [2], [3, 8, [[4]], 9], [5, 6]];
const result = [];
const stack = [{current: input, pos: 0}];
while (stack.length > 0) {
let {current, pos} = stack.pop();
if (pos < current.length) {
let item = current[pos++];
stack.push({current, pos});
if (Array.isArray(item)) {
stack.push({current: item, pos: 0});
} else {
result.push(item);
}
}
}
console.log(result);
This is what a recursive approach would do in the background, more or less. If your concern about recursion was that you don't like/understand it, not sure that you will find this one more likeable.