You pass the wrong first argument result.push.apply:
result.push.apply(array, flatten(current));
You want to call pushon result, but actually you call array.push. You want to say:
result.push.apply(result, flatten(current));
so it pushgets resultits own thiswhen it is called.
A more interesting question is why your based implementation is forโworking,โ even if its implementation is confused. If you throw it away
console.log(nested);
, , for ; , "".
if:
if (Array.isArray(current)) {
result.push.apply(array, flatten(current));
}
else {
result.push(current);
}
, array, . , array, , - result, .
:
var nested = [1, [2], [3, [[[4]]]], 5]
, -, :
[1, 5, 2, 3, 4]
( nested). , for, , .