My goal is to write a function that will flat an array. So for example [1,[2,3]] should turn to [1,2,3]. I tried it with a recursive method as seen below, but it produces an endless loop.
function steamrollArray(arr) {
var resultArray = [];
function flatArray(array) {
for (i = 0; i < array.length; i++){
if (Array.isArray(array[i])) {
flatArray(array[i]);
} else resultArray.push(array[i]);
}
}
flatArray(arr);
return resultArray;
}
steamrollArray([1, [2,3]]);
What is my mistake?
Thanks in advance
Array.prototype.reduce.steamrollArray([1, [2, 3]])produces[1, 2, 3]as expected.iis global, hence every call toflatArraymakes it start from zero.