I'm trying to flatten nested arrays while preserving the order, e.g. [[1, 2], 3, [4, [[5]]]]
should be converted to [1, 2, 3, 4, 5]
.
I'm trying to use recursion in order to do so, but the code below does not work and I don't understand why. I know there are other methods to do it, but I'd like to know what's wrong with this.
function flatten (arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
flatten(arr);
} else {
newArr.push(arr[i]);
}
}
return newArr;
}
flatten([[1, 2], 3, [4, [[5]]]]);
Thanks